Slide 1

Slide 1 text

Static & Singleton Java/Kotlin Yair Palti

Slide 2

Slide 2 text

Static in Java The keyword static indicates that the particular 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

Slide 3

Slide 3 text

Reasons to Use static Fields ● When the value of variable is independent of instances ● When the value is supposed to be shared across all instances static String className = “MyClass” static Int prefixPhoneNumber= 972

Slide 4

Slide 4 text

The static Methods Static methods also belong to a class instead of the instance and so they can be called without creating the instance of the class in which they reside.

Slide 5

Slide 5 text

Reasons to Use static Methods ● To access/manipulate static variables and other static methods that don’t depend upon instances. ● static methods are widely used in utility and helper classes

Slide 6

Slide 6 text

Example of static Method static methods are generally used to 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; }

Slide 7

Slide 7 text

Kotlin Static

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

Kotlin Static Companion Object

Slide 10

Slide 10 text

Singleton The singleton pattern is a design pattern that restricts 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?

Slide 11

Slide 11 text

Java - simple singleton example public class MySingletonClass{ private MySingletonClass() {} private static MySingletonClass instance; public static MySingletonClass getInstance() { if (instance == null) { instance = new MySingletonClass(); } return instance; } }

Slide 12

Slide 12 text

Java - a thread-safe singleton version public class MySingletonClass{ private static MySingletonClass instance = null; private MySingletonClass() {} private synchronized static void createInstance() { if (instance == null) { instance = new MySingletonClass(); } } public static MySingletonClass getInstance() { if (instance == null) createInstance(); return instance; } }

Slide 13

Slide 13 text

Kotlin - Singleton What would be the equivalent in Kotlin? object MySingletonClass * Object declaration

Slide 14

Slide 14 text

Static example (Java) public final class PupilJava { private String name; private static int counter; private static void count() {counter++;} public static int howMany() { return counter;} public final String getName() { return this.name; } public final void setName(String var1) { this.name = var1; } public PupilJava(String name) { this.name = name; count(); } };

Slide 15

Slide 15 text

Companion Object class Pupil (var name:String) { init { count() } companion object { private var counter: Int = 0 private fun count() = counter++ fun howMany(): Int { return counter } } } fun main(args: Array){ val p1 = Pupil("Yair") val p2 = Pupil("Eran") println("Pupils: ${Pupil.howMany()}") } Output: Pupils: 2

Slide 16

Slide 16 text

companion object is a singleton instance of an actual object Companion Object

Slide 17

Slide 17 text

Companion Object vs Object Companion object has these characteristics: ● Unable to stand by itself ● Is loaded with the class Object has these characteristics: ● Able to stand by itself ● Lazy

Slide 18

Slide 18 text

Objects vs. File level properties/methods class Example { companion object { const val CONSTANT = "something" } const val CONSTANT = "something" class Example { } VS.

Slide 19

Slide 19 text

Calling Kotlin from Java - Package-Level Functions functions and properties 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();

Slide 20

Slide 20 text

Calling Kotlin from Java - Static fields Kotlin properties Static fields @JvmField lateinit const

Slide 21

Slide 21 text

Calling Kotlin from Java - Static fields Annotating such a 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 = compareBy { it.value } }} // Java Key.COMPARATOR.compare(key1, key2); // public static final field in Key class

Slide 22

Slide 22 text

Calling Kotlin from Java - Static fields object Singleton { lateinit var provider: Provider } // Java Singleton.provider = new Provider(); // public static non-final field in Singleton class

Slide 23

Slide 23 text

Calling Kotlin from Java - Static fields Properties annotated with 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;

Slide 24

Slide 24 text

Calling Kotlin from Java - Static Methods Kotlin can generate 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

Slide 25

Slide 25 text

Calling Kotlin from Java - Static Methods Same for named 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

Slide 26

Slide 26 text

Objects - construction & deletion Garbage Collection Constructor Object

Slide 27

Slide 27 text

Kotlin singletons with argument Contrary to a Kotlin class, an object can’t have any constructor, but init blocks can be used if some initialization code is required. object SomeSingleton { init { println("init complete") } }

Slide 28

Slide 28 text

Kotlin singletons with argument - Android use case you often need to pass a Context instance to initialization blocks of singleton components

Slide 29

Slide 29 text

Kotlin singletons with argument - Android use case Early initialization Application.onCreate() In

Slide 30

Slide 30 text

Android - Singleton usage In a typical Android app, there are many objects for which we only need one global instance Retrofit

Slide 31

Slide 31 text

Android - Singleton example It can be used when we need our object to store sessions, database connections, communication protocols, etc. Example object PersistenceManager

Slide 32

Slide 32 text

Thank you ! Yair Palti https://www.linkedin.com/in/yairpalti/