We will review Static & Singleton usage in Java and in related thread safety and OOD.
We will see the equivalent in Kotlin and review the differences.
Also, we will see some Android Kotlin usage
member belongs to a Class itself, rather than to an instance of that class. This means that only one instance of that static member is created which is shared across all instances of the class
variable is independent of instances • When the value is supposed to be shared across all instances static String className = “MyClass” static Int prefixPhoneNumber= 972
perform an operation that is not dependent upon instance creation. public class Car{ private static int numberOfCars = 0; public static void setNumberOfCars(int numberOfCars) { Car.numberOfCars = numberOfCars; }
the instantiation of a class to one instance. This is useful when exactly one instance is needed to coordinate actions across the system. The singleton design pattern solves problems like: • How can it be ensured that a class has only one instance? • How can the sole instance of a class be accessed easily? • How can a class control its instantiation?
declared in a file compiled into static methods of a Java class // example.kt package demo class Foo { } fun bar() { ... } // Java new demo.Foo(); demo.ExampleKt.bar();
property with @JvmField makes it a static field with the same visibility as the property itself class Key(val value: Int) { companion object { @JvmField val COMPARATOR: Comparator<Key> = compareBy<Key> { it.value } }} // Java Key.COMPARATOR.compare(key1, key2); // public static final field in Key class
const (in classes as well as at the top level) are turned into static fields in Java // file example.kt object Obj { const val CONST = 1 } class C { companion object { const val VERSION = 9 } } const val MAX = 239 In Java int c = Obj.CONST; int d = ExampleKt.MAX; int v = C.VERSION;
static methods for functions defined in named objects or companion objects if you annotate those functions as @JvmStatic class C { companion object { @JvmStatic fun foo() {} fun bar() {} } } Now, foo() is static in Java, while bar() is not: C.foo(); // works fine C.bar(); // error: not a static method C.Companion.foo(); // instance method remains C.Companion.bar(); // the only way it works
objects: object Obj { @JvmStatic fun foo() {} fun bar() {} } In Java Obj.foo(); // works fine Obj.bar(); // error Obj.INSTANCE.bar(); // works, a call through the singleton instance Obj.INSTANCE.foo(); // works too
object can’t have any constructor, but init blocks can be used if some initialization code is required. object SomeSingleton { init { println("init complete") } }