【问题标题】:How to create an anonymous implementation of an interface?如何创建接口的匿名实现?
【发布时间】: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,我知道该怎么做,但我希望类型具有描述性名称,而不仅仅是函数签名。

【问题讨论】:

    标签: interface kotlin


    【解决方案1】:

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

    请注意,与文档中的示例不同,object : TileSet 后面没有括号。

    【讨论】:

    • 我收到Object must be declared abstract or implement abstract member public abstract operator. 为什么?
    • @danielgomezrico 那一定是因为你的基类/接口(在我的例子中是TileSet)声明了一个抽象方法,你应该在你的匿名实现中实现它。
    【解决方案2】:

    我做了一点实验,我惊讶地发现你可以使用 Kotlin lambdas 实现 Java 函数式接口:

    // Implementing Java functional interfaces using lambdas
    val greeter = Consumer<String> { println("Hi $it") }
    val dice = Supplier { ThreadLocalRandom.current().nextInt(1, 7) }
    

    但是当你实现Kotlin功能接口时,你需要完整的仪式:

    // Implementing a Kotlin functional inteface with lambdas is not possible
    val greeter = object : MyConsumer<String> {
        override fun accept(x: String) {
            println("Hi $x")
        }
    }
    
    @FunctionalInterface
    interface MyConsumer<T> {
        fun accept(x:T)
    }
    

    我想知道为什么从 Kotlin 实现 Kotlin 接口时需要完整的匿名类语法!

    也许他们希望您改用函数?可以这样做。

    // If you want to use lambdas, define a function instead of an interface
    val greeter: MyConsumerFunction<String> = { println("Hi $it") }
    
    typealias MyConsumerFunction<T> = (T) -> Unit
    

    无论如何,如果有人对此有所了解,请告诉我! :)

    【讨论】:

    • 是的,每次遇到这个我都会生气。我知道常规函数更惯用,但是当您处理依赖注入框架(如旧版本的 Guice 和 Spring)时,它们不能与 Kotlin 函数一起使用,那么声明接口总体上更容易,除非涉及到创建实现这些接口。有时我只是在 Java 文件中创建接口,这样我就可以避免 Kotlin 仪式......
    【解决方案3】:

    用kotlin是可以的,只是你必须在interface之前加上fun所以就像fun interface xx,它被称为函数接口,基本上它的意思是一个带有ONE函数的接口,这就是我们通常想要

    https://kotlinlang.org/docs/fun-interfaces.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多