Kotlin功能接口Java兼容性 [英] Kotlin functional interfaces java compatiblity

查看:144
本文介绍了Kotlin功能接口Java兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Kotlin上开发应用程序,但是需要良好的Java支持. 我发现的问题是kotlin的功能.

I work on an application in kotlin, but need to have a good java support. The problem I found are kotlin's functions.

这是我曾经做过的

fun test(loader: (String) -> Int)

但是它将从kotlin库编译为Function1,并且由于jar的大小,我没有在jar中直接包含kotlin库,这使Java开发人员更加困难,因为他们必须下载kotlin库才能使用这种方法.

but this will compile into a Function1 from kotlin library and since I don't have kotlin library directly included in the jar because of jar size, it makes it harder for java developers because they have to download the kotlin library to be able to use this method.

我尝试使用Java的Supplier或Function接口,但是我发现kotlin开发人员要困难得多,因为您必须提供更多的变量类型和null检查,以及通用参数,这很痛苦..

I tried to use Supplier or Function interface from java but I found it a lot more difficult for kotlin developers since you have to provide a lot more variable types and null checks and together with generic arguments it's a pain..

还尝试创建自己的界面,例如

Also tried to create my own interface like

@FunctionalInterface
interface Function<in T, out R>: Function<R> {
    operator fun invoke(p: T): R
}

和功能

fun test(loader: Function<String, Int>)

但与默认的Java Function接口相同

but it's the same as default java Function interface

因此,唯一可行的方法是让编译器将我的原始函数编译为我自己的函数接口,而不是kotlin的函数接口.但是我不知道该怎么做.

so the only way that could work is to let the compiler compile my original function to my own functional interface instead of kotlin's one. But I don't have idea how to do that.

推荐答案

在kotlin 1.4中,他们增加了定义这样自己的功能接口的功能

In kotlin 1.4 they added ability to define our own functional interfaces like that

fun interface Function<in T, out R> {

    operator fun invoke(p: T): R
}

fun test(loader: Function<String, Int>) {
    val result = loader("5")
}

这篇关于Kotlin功能接口Java兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆