科特林的实用程序类 [英] Utils class in Kotlin

查看:67
本文介绍了科特林的实用程序类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Java, we can create an utilities class like this:

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

但是如何在Kotlin中做到这一点?

But how to do this in Kotlin?

我尝试在object中使用函数:

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

但是从Java代码调用此方法时,需要添加INSTANCE.例如:Utils.INSTANCE.foo().

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

然后我将其声明为顶级函数(没有classobject):

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

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

fun foo(): Boolean {
    return true
}

然后我可以从Java代码中调用Utils.foo().但是从Kotlin代码中,我得到了Unresolved reference编译器错误.只能直接使用foo()函数(不带Utils前缀).

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

So what is the best approach for declaring utils class in Kotlin?

推荐答案

您提出的最后一个解决方案实际上在Kotlin中是非常惯用的-无需将函数范围限制在任何东西内,顶级函数可以很好地用于实际上,大多数标准库都是由实用程序组成的.

The last solution you've proposed is actually quite idiomatic in Kotlin - there's no need to scope your function inside anything, top level functions are just fine to use for utilities, in fact, that's what most of the standard library consists of.

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

You've used the @JvmName annotation the right way too, that's exactly how you're supposed to make these top level functions easily callable for Java users.

请注意,如果要将顶级函数放在不同的文件中,但仍然希望它们最终归为同一类文件(同样,仅适用于Java用户),则只需要@JvmMultifileClass.如果您只有一个文件,或者每个文件使用不同的名称,则不需要此注释.

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.

如果出于某种原因,您想要在Java和Kotlin中使用相同的Utils.foo()语法,则使用object然后使用@JvmStatic的解决方案是解决问题的方法,如@marianosimone在此答案.

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.

这篇关于科特林的实用程序类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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