فاطمه معمار
فاطمه معمار
خواندن ۲ دقیقه·۲ سال پیش

lateinit vs lazy

lateinit vs lazy

  1. lateinit Use it with mutable variable[var]lateinit var name: String //Allowed
    lateinit val name: String //Not Allowed

because it can't be compiled to a final field

- Allowed with only non-nullable data types

lateinit var name: String //Allowed lateinit var name: String? //Not Allowed

- It is a promise to compiler that the value will be initialized in future.

NOTE: If you try to access lateinit variable without initializing it then it throws UnInitializedPropertyAccessException.

-Lateinit does not allocate memory before initializing.

-Lateinit cannot be used for non-primitive datatypes, i.e., Long and int.

-If you want your property to be initialized from outside in a way probably unknown beforehand, use lateinit.

-lateinit var can be initialized from anywhere the object is seen from, e.g. from inside a framework code, and multiple initialization scenarios are possible for different objects of a single class.

-If you want your property to be initialized from outside in a way probably unknown beforehand, use lateinit.

-lateinit is for external initialisation: when you need external stuff to initialise your value by calling a method.

2)by lazy { ... }

- Lazy initialization was designed to prevent unnecessary initialization of objects

- In the Lazy initialization, your variable will not be initialized unless you call/use it.

- Your variable will not be initialized unless you use it.

- It is initialized only once. Next time when you use it, you get the value from cache memory.

- It is thread safe(It is initialized in the thread where it is used for the first time. Other threads use the same value stored in the cache).

- The variable can only be val.

- The variable can only be non-nullable.

-by lazy { ... }, in turn, defines the only initializer for the property, which can be altered only by overriding the property in a subclass.

-While lazy is when it only uses dependencies internal to your object.



--NOTE

  • “val” is used to define Immutable data. It’s evaluated only once at the time of definition.
  • “var” is used to define Mutable data. It’s evaluated only once at the time of definition.
  • “lazy val” is used to define Immutable data. It is evaluated only once when we access it for first time. That means it is evaluated Lazily.


name stringevaluated onceinitialized fromstring allowedlateinit
شاید از این پست‌ها خوشتان بیاید