Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Static & Singleton in Java vs Kotlin

Avatar for Yair Yair
September 10, 2018

Static & Singleton in Java vs Kotlin

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

Avatar for Yair

Yair

September 10, 2018
Tweet

Other Decks in Programming

Transcript

  1. 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
  2. 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
  3. 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.
  4. 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
  5. 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; }
  6. 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?
  7. 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; } }
  8. 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; } }
  9. Kotlin - Singleton What would be the equivalent in Kotlin?

    object MySingletonClass * Object declaration
  10. 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(); } };
  11. 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<String>){ val p1 = Pupil("Yair") val p2 = Pupil("Eran") println("Pupils: ${Pupil.howMany()}") } Output: Pupils: 2
  12. 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
  13. Objects vs. File level properties/methods class Example { companion object

    { const val CONSTANT = "something" } const val CONSTANT = "something" class Example { } VS.
  14. 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();
  15. 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<Key> = compareBy<Key> { it.value } }} // Java Key.COMPARATOR.compare(key1, key2); // public static final field in Key class
  16. 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
  17. 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;
  18. 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
  19. 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
  20. 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") } }
  21. Kotlin singletons with argument - Android use case you often

    need to pass a Context instance to initialization blocks of singleton components
  22. Android - Singleton usage In a typical Android app, there

    are many objects for which we only need one global instance Retrofit
  23. Android - Singleton example It can be used when we

    need our object to store sessions, database connections, communication protocols, etc. Example object PersistenceManager