在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类的最佳方法是什么呢?