Singleton class in Kotlin

后端 未结 8 1878
梦如初夏
梦如初夏 2020-12-14 13:47

I want to know way to create singleton class, so that my Util class instantiate only once per app. However when I converted my Java class to kotlin, below code was generated

8条回答
  •  星月不相逢
    2020-12-14 14:31

    In Kotlin you should get rid of the whole notion of the utility singleton class. The idiomatic way is to simply move all declarations to the top level.

    Java:

    public final class Util {
        public static final Util UTIL = new Util();
    
        private int prefixLength = 4;
    
        private Util() {}
    
        public void setPrefixLength(int newLen) {
            prefixLength = newLen;
        }
    
        public String extractVin(String input) {
            return input.substring(prefixLength);
        }
    }
    

    Usage:

    String vin = UTIL.extractVin("aoeuVN14134230430")
    

    In Kotlin just create a separate file called util.kt with the following:

    var prefixLength = 4
    
    fun String.extractVin() = this.substring(prefixLength)
    

    Usage:

    val vin = "aoeuVN14134230430".extractVin()
    

    But... you're polluting the top-level namespace!

    If your Java intuition triggers a red flag here, simply remember that the package is the namespacing construct and as opposed to Java, Kotlin doesn't conflate the concerns of namespacing and encapsulation. There's no "package-private" access level so you're free from the burden of deciding that something must stay within the same package so it can be made package-private.

    So, where in Java you create a degenerate class as a workaround, in Kotlin you just create a file in its own package.

提交回复
热议问题