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

查看:32
本文介绍了从 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.

与 kotlin 中的静态函数一起使用是有效的:

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"<​​/em> 扩展名替换为 "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 编译器将看到名为 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天全站免登陆