在Java中,我们可以创建如下实用程序类:

final class Utils {
    public static boolean foo() {
        return false;
    }
}

但是在Kotlin 怎么做到这一点呢?


I try using functions inside object:

object Utils {
    fun foo(): Boolean {
        return false
    }
}

But when call this method from Java code it need to add INSTANCE. Ex: Utils.INSTANCE.foo().


Then I change to declare it as top-level function (without class or object):

@file:JvmName("Utils")
@file:JvmMultifileClass

fun foo(): Boolean {
    return true
}

Then I can call Utils.foo() from Java code. But from Kotlin code I got Unresolved reference compiler error. It only allow be to use foo() function directly (without Utils prefix).


那么,在Kotlin中声明utils类的最佳方法是什么呢?

推荐答案

您提出的最后一个解决方案实际上在Kotlin中非常惯用——不需要在任何内容中定义您的函数,顶级函数可以用于实用程序,事实上,这是大多数标准库的组成部分.

您也以正确的方式使用了@JvmName注释,这正是让Java用户可以轻松调用这些顶级函数的方法.

Note that you only need @JvmMultifileClass if you are putting your top level functions in different files but still want them to end up grouped in the same class file (again, only for Java users). If you only have one file, or you're giving different names per file, you don't need this annotation.


If for some reason you want the same Utils.foo() syntax in both Java and Kotlin, the solution with an object and then @JvmStatic per method is the way to do that, as already shown by @marianosimone in this answer.

Kotlin相关问答推荐

Fleet无法从构建文件自动重新加载更改错误'

为什么Kotlin协程程序即使有延迟也能输出?

禁用 Gradle执行消息

Mockk:对同一函数进行两次存根会忽略第一个行为

在kotlin中匹配多个变量

Kotlin 如何使用其 get 函数在内部检索映射值

Kotlin Path.useLines { } - 如何不获取 IOException("Stream closed")?

Kotlin 数据类中的大量参数

在jetpack compose中将默认方向设置为横向?

PRDownloader 即使在实现库后也无法工作.未知参考:Android Studio 中的 PRDownloader

Kotlin 插件之间的区别

Mixin 在 Jackson 中添加 defaultImpl 不起作用

如何在kotlin中使用协程每秒调用一个函数

在 kotlin 中模拟伴随对象函数

在Kotlin中传递并使用函数作为构造函数参数

API 26 上未显示 Android 通知

如果作为 RxJava Observable 提供,Kotlin 密封类子类需要强制转换为基类

如何限制kotlin协程的最大并发性

WebFlux 功能:如何检测空 Flux 并返回 404?

如何在 Kotlin 中将串联转换为模板