Kotlin 中的实用程序类 [英] Utils class in Kotlin

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

问题描述

在 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 中使用函数:

I try using functions inside 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<的解决方案/code> 每个方法都是这样做的方法,正如@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.

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

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