如果 Java 互操作是最高优先级,我要么直接使用 Java 功能接口(即Consumer、Supplier 等),要么现在创建自定义 Kotlin functional interfaces。同时 Kotlin 更好地处理函数式接口......
Java 变体:
interface Foo{
fun bar(x : java.util.function.Consumer<String>)
}
// calling this from Kotlin today looks the same as if we used (String) -> Unit:
foo.bar { println(it) }
带有自定义 Consumer 的 Kotlin 变体:
fun interface MyConsumer<T> { // just a demo... probably depends on your needs
fun accept(t : T)
// other functions?
}
用法同上。也许今天还有一种更简单的方法可以将(String) -> Unit 之类的东西处理为Consumer<String>,但是我还不知道(或者觉得还没有必要研究它;-))。 Ilya 在 cmets 中提到的编译器注释可能是一种集中解决此问题的方法。
在 2018 年 12 月,我写道:我对此没有真正的答案,但我会分享,在需要从 Java 访问此类 Kotlin 代码的情况下我做了什么(或者我想到了什么) .
基本上,这取决于您真正想要触摸/增强哪一侧以获得您需要的东西。
增强 Kotlin 代码以支持 Java 等效项:
interface Foo {
fun bar(x : (String) -> Unit)
/* the following is only here for Java */
@JvmDefault // this requires that you add -Xjvm-default=enable to your compiler flags!
fun bar(x:Consumer<String>) = bar(x::accept)
}
这有一些缺点:Consumer-方法在 Kotlin 中也是可见的,因此也可以从那里调用。不用说,您需要复制接口中的所有功能,因此您的整个 Kotlin 接口只会变得更加臃肿。但是:它以您期望的方式从双方工作。 Java 调用 Consumer-variant,Kotlin 调用 (String) -> Unit-variant...希望 ;-) 实际上只是演示了一些调用:
// from Java:
..bar(s -> { System.out.println(s); })
// however, method references might not work that easily or not without a workaround...
..bar((Consumer<String>) System.out::println); // not nice... @JvmName("kotlinsBar") to the rescue? well... that will just get more and more ugly ;-)
// from Kotlin:
..bar(Consumer(::println)) // or: ..bar(Consumer { println(it) })
..bar(::println) // or: ..bar { println(it) } // whatever you prefer...
话虽如此,另一个变体是添加帮助方法,这些方法实际上有助于更轻松地从 Java 调用 Kotlin 函数,例如如下:
fun <T> `$`(consumer: Consumer<T>): (T) -> Unit = consumer::accept
这可能永远不会从 Kotlin 调用(因为编写反引号和 $ 已经够麻烦了)或者如果你不想让你的 Kotlin 代码膨胀,只需将这样的方法添加到 Java,但它不会看起来那么苗条:
static <T> Function1<T, Unit> $(Consumer<T> consumer) {
return t -> {
consumer.accept(t);
return Unit.INSTANCE;
};
}
对这些方法的调用看起来都一样:
..bar($(s -> /* do something with s */)) // where bar(x : (String) -> Unit)
对于我需要解决的问题,我只返回了 Unit.INSTANCE 或 null,但如果我有更多方法可以调用,我可能会选择第二种 ($(...)) 方法。在最好的情况下,我只需要提供(生成?;-))等价物一次并在多个项目中使用它们,而在接口中为 Java 提供default 变体可能需要更多的工作,甚至可能会让一些人感到困惑.. .
最后:不...我不知道有任何选项可以让您在 Kotlin 的 Unit-returning 功能接口之外拥有类似 void-functional interfaces (/consumers) 的东西。