java扩展函数,从Java访问Kotlin扩展函数

Is it possible to access extension functions from Java code?

I defined the extension function in a Kotlin file.

package com.test.extensions

import com.test.model.MyModel

/**

*

*/

public fun MyModel.bar(): Int {

return this.name.length()

}

Where MyModel is a (generated) java class.

Now, I wanted to access it in my normal java code:

MyModel model = new MyModel();

model.bar();

However, that doesn't work. The IDE won't recognize the bar() method and compilation fails.

What does work is using with a static function from kotlin:

public fun bar(): Int {

return 2*2

}

by using import com.test.extensions.ExtensionsPackage so my IDE seems to be configured correctly.

I searched through the whole Java-interop file from the kotlin docs and also googled a lot, but I couldn't find it.

What am I doing wrong? Is this even possible?

解决方案

All Kotlin functions declared in a file will be compiled by default to static methods in a class within the same package and with a name derived from the Kotlin source file (First letter capitalized and ".kt" extension replaced with the "Kt" suffix). Methods generated for extension functions will have an additional first parameter with the extension function receiver type.

Applying it to the original question, Java compiler will see Kotlin source file with the name example.kt

package com.test.extensions

public fun MyModel.bar(): Int { /* actual code */ }

as if the following Java class was declared

package com.test.extensions

class ExampleKt {

public static int bar(MyModel receiver) { /* actual code */ }

}

As nothing happens with the extended class from the Java point of view, you can't just use dot-syntax to access such methods. But they are still callable as normal Java static methods:

import com.test.extensions.ExampleKt;

MyModel model = new MyModel();

ExampleKt.bar(model);

Static import can be used for ExampleKt class:

import static com.test.extensions.ExampleKt.*;

MyModel model = new MyModel();

bar(model);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值