如何创建一个接口的匿名实现? [英] How to create an anonymous implementaiton of an interface?
问题描述
我有一个界面:
interface TileSet {
fun contains(x: Int, y: Int) : Boolean
}
我希望能够创建多组瓷砖(瓷砖)是一对x和y整数坐标):
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中,我可以这样做:
In Java 8, I could do it like this:
@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);
}
}
因此,接口是用<$ $中的lambda实现的C $ C>地形设置#团结()。或者它可以用旧的匿名类方法实现:
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中实现单方法接口?
How can I create an anonymous implementation of a single-method interface in Kotlin?
如果我使用(Int,Int) - >我知道怎么做Boolean
而不是 TileSet
,但我希望该类型具有描述性名称而不仅仅是函数签名。
I know how to do it if I use (Int, Int) -> Boolean
instead of TileSet
, but I want the type to have a descriptive name rather than just a function signature.
推荐答案
中有一些示例匿名类的文档,但不适用于接口。
这是我创建接口实例的方式:
This is how I created an instance of an interface:
fun TileSet.union(another: TileSet) : TileSet =
object : TileSet {
override fun contains(x: Int, y: Int) : Boolean =
this@union.contains(x, y) || another.contains(x, y)
}
请注意,与示例不同文档,对象后没有括号:TileSet
。
Notice that, unlike in the example from documentation, there are no parentheses after object : TileSet
.
这篇关于如何创建一个接口的匿名实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!