我有一个界面:
interface TileSet {
fun contains(x: Int, y: Int) : Boolean
}
I want to be able to create unions of sets of tiles (tile is a pair of x and y integer coordinates):
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);
}
}
So an interface is implemented with a lambda in TileSet#unite()
. Or it could be implemented with the old anonymous class approach:
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
,我知道该怎么做,但我希望类型具有描述性名称,而不仅仅是函数签名.