kotlin 不兼容java,Kotlin功能接口Java兼容性

I work on an application in kotlin, but need to have a good java support.

The problem I found are kotlin's functions.

this is what I used to do

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

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.

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: Function {

operator fun invoke(p: T): R

}

and function

fun test(loader: Function)

but it's the same as default java Function interface

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.

解决方案

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

fun interface Function {

operator fun invoke(p: T): R

}

fun test(loader: Function) {

val result = loader("5")

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值