I have the following class
class Book implement Borrowable {
@Override
public String toString(Function<? extends Borrowable
, String> format) {
return format.apply(this);
}
}
This gives me an error that i cannot use "apply" on this(Book object).
My current formatter is
Function<Book, String> REGULAR_FORMAT = book -> "name='" + book.name + '\'' +
", author='" + book.author + '\'' +
", year=" + book.year;
I don't want to make the lambda function of the type
Function<Borrowable, String>
as I would lose access to the members of Book not exposed by Borrowable.
A lambda expression can't specify type parameters, so it's not generic. However, a functional interface associated with lambda expression is generic.
The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type.
In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific).
Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection .
The Function<? extends Borrowable, String>
type means function that able to accept some type which extends Borrowable
. It does not mean that it accepts Book
. Probably the best solution is to introduce the generic parameter for Borrowable
:
public interface Borrowable<T> {
public String toString(Function<? super T, String> format);
}
And specify it in Book
:
public class Book implements Borrowable<Book> {
@Override
public String toString(Function<? super Book, String> format) {
return format.apply(this);
}
}
It's similar to how the Comparable
interface works.
You might be looking for Function<? super Book, String>
.
A Function<Book, String>
is a valid Function<? extends Borrowable, String>
, but so is a Function<DVD, String>
. Your method (toString
) might be called with a Function<DVD, String>
, which you can't pass this
to because this
isn't a DVD
!
Change the argument type to Function<? super Book, String>
, perhaps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With