【发布时间】:2016-02-06 17:52:13
【问题描述】:
我有一个界面:
interface TileSet {
fun contains(x: Int, y: Int) : Boolean
}
我希望能够创建图块集的并集(图块是一对 x 和 y 整数坐标):
fun TileSet.union(another: TileSet) : TileSet =
// ..
在 Java 8 中,我可以这样做:
@FunctionalInterface
public interface TileSet {
boolean contains(int x, int y);
public default TileSet unite(TileSet another) {
return (x, y) -> TileSet.this.contains(x, y) && another.contains(x, y);
}
}
所以一个接口是用 TileSet#unite() 中的 lambda 实现的。或者它可以用旧的匿名类方法来实现:
public default TileSet unite(TileSet another) {
return new TileSet() {
@Override
public boolean contains(int x, int y) {
return TileSet.this.contains(x, y) && another.contains(x, y);
}
}
}
如何在 Kotlin 中创建单方法接口的匿名实现?
如果我使用 (Int, Int) -> Boolean 而不是 TileSet,我知道该怎么做,但我希望类型具有描述性名称,而不仅仅是函数签名。
【问题讨论】: