我有一个界面:

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,我知道该怎么做,但我希望类型具有描述性名称,而不仅仅是函数签名.

推荐答案

documentation中有匿名类的例子,但没有接口的例子.

下面是我创建接口实例的方式:

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)
    }

Notice that, unlike in the example from documentation, there are no parentheses after object : TileSet.

Kotlin相关问答推荐

Regex(Kotlin)仅匹配句子末尾的句号,而忽略中间的句号,如缩写

在Webflux应用程序中通过kotlin协程启动fire and forget job

如何编写带有依赖项的自定义Kotlin串行化程序?

如何通过更改现有数据类型来执行Android房间数据库迁移?

为什么在jacksonObjectMapper上将DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES设置为false无效?

可以在没有导入声明的情况下调用 Kotlin 扩展函数吗?

如果带注释的成员未被特定块包围,则发出 IDE 警告

kotest 更改环境变量

如果不为空,则为 builder 设置一个值 - Kotlin

在 kotlin 中模拟伴随对象函数

使用 Hilt 注入 CoroutineWorker

来自类型参数的属性的自定义 getter

kotlin,如何从函数返回类类型

如何通过反射使用 Kotlin 对象

Kotlin默认使用哪种排序?

Kotlin - 来自 KType 的 KClass<*>

Kotlin 扩展函数 - 覆盖现有方法

Kotlin 接口属性:只需要公共 getter 而没有公共 setter

Kotlin Flow 收集后无法执行代码

如何在 firebase 数据库中使用 kotlin 协程