I am confuse for lateinit and nullable variable, which one to use for variable.
lateinit var c: String
var d: String? = null
c = \"UserDefinedTarget\"
// if
It depends.
Nullable variable means that variable can hold value or null. lateinit
means that variable must be initialised later. It should be initialized before accessing it. If you attempt accessing uninitialized lateinit
variable UninitializedPropertyAccessException
will be thrown.
It's always better to avoid using nulls in your app. Nulls are evil. So if you can initialize variable in onCreate
then it's better to use lateinit
. Also if you use dependency injection in your app and fields should be injected it's also a valid case to use lateinit
instead of handling nulls.
If for some reason you can't initialize variable, initializing code can result to null, or null can be assigned to this variable later than you should use nullable variable. Generally speaking if null is a valid value for the variable.