Java 8:Lambda函数和通用通配符 [英] Java 8 : Lambda Function and Generic Wildcards
问题描述
我有以下课程
class Book implement Borrowable {
@Override
public String toString(Function<? extends Borrowable
, String> format) {
return format.apply(this);
}
}
这给了我一个错误,我不能在此(Book对象)上使用应用".
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;
我不想创建类型为lambda的函数
I don't want to make the lambda function of the type
Function<Borrowable, String>
因为我将无法访问未借阅的Book成员.
as I would lose access to the members of Book not exposed by Borrowable.
推荐答案
Function<? extends Borrowable, String>
类型表示能够接受扩展Borrowable
的 some 类型的函数.这并不意味着它接受Book
.可能最好的解决方案是为Borrowable
引入通用参数:
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);
}
并在Book
中指定它:
public class Book implements Borrowable<Book> {
@Override
public String toString(Function<? super Book, String> format) {
return format.apply(this);
}
}
这与Comparable
界面的工作方式类似.
It's similar to how the Comparable
interface works.
这篇关于Java 8:Lambda函数和通用通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!