Utils class in Kotlin

后端 未结 3 1312
暖寄归人
暖寄归人 2021-01-01 09:34

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

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

Bu

3条回答
  •  天涯浪人
    2021-01-01 09:54

    Note that the util class you used in Java was the only way to supply additional functions there, for anything that did not belong to a particular type or object. Using object for that in Kotlin does not make any sense. It isn't a singleton, right?

    The second approach you mentioned is rather the way to go for utility functions. Internally such functions get translated to static ones and as you can see they become the static util classes in Java you are searching for, as you can't have standalone functions in Java without a class or enum. In Kotlin itself however they are just functions.

    Some even count utility classes to the anti-patterns. Functions on the other hand make totally sense without a class or object whose name hasn't so much meaning anyway.

提交回复
热议问题