从Java访问Kotlin扩展函数 [英] Accessing Kotlin extension functions from Java

查看:2693
本文介绍了从Java访问Kotlin扩展函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从Java代码访问扩展函数?

Is it possible to access extension functions from Java code?

我在Kotlin文件中定义了扩展函数。

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

其中 MyModel 是(生成的)java类。
现在,我想用我的普通java代码访问它:

Where MyModel is a (generated) java class. Now, I wanted to access it in my normal java code:

MyModel model = new MyModel();
model.bar();

但是,这不起作用。 IDE无法识别 bar()方法,编译失败。

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

使用来自ko​​tlin的静态函数的工作是什么:

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

public fun bar(): Int {
   return 2*2
}

使用 import com.test.extensions .ExtensionsPackage 所以我的IDE似乎配置正确。

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

我搜索了kotlin文档中的整个Java-interop文件,并搜索了一个很多,但我找不到。

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?

推荐答案

默认情况下,文件中声明的所有Kotlin函数都会编译为类中的静态方法相同的包和名称来源于Kotlin源文件(首字母大写且。kt扩展名替换为Kt后缀)。为扩展函数生成的方法将具有扩展函数接收器类型的附加第一个参数。

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.

将其应用于原始问题,Java编译器将看到名称为Kotlin的源文件 example.kt

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 */ }

如同以下Java类声明

as if the following Java class was declared

package com.test.extensions

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

没有任何反应从Java的角度来看,使用扩展类,您不能只使用点语法来访问这些方法。但它们仍然可以作为普通的Java静态方法调用:

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

静态导入可用于ExampleKt类:

Static import can be used for ExampleKt class:

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

MyModel model = new MyModel();
bar(model);

这篇关于从Java访问Kotlin扩展函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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