A Gamal
01/09/2019, 10:24 AMlateinit
? I use isInitialized
everytime I access lateinit
, so I wonder if I could optimize that and only do the check once. In case of a nullable type, I could do something like that.nfrankel
01/09/2019, 10:32 AMPavlo Liapota
01/09/2019, 10:33 AMlateinit
if you always check isInitialized
? Just use nullable type and check != null
.
And why do you throw exception in your example? Just use lateinit
and exception will be thrown if field is not initialized.A Gamal
01/09/2019, 10:48 AMisInitialized
once and throw a custom exception if not initialized, same if it would be nullable type in code snippet.nfrankel
01/09/2019, 10:49 AMNotInitializedException
if i remember correctlyA Gamal
01/09/2019, 10:56 AMlateinit
as the object is being set later in a setter and MUST not be null.Pavlo Liapota
01/09/2019, 10:58 AMDelegates.notNull
as an example.A Gamal
01/09/2019, 11:03 AMA Gamal
01/09/2019, 11:14 AMDelegates.notNull
would work. Thank you.Mike
01/09/2019, 12:28 PMlateinit
is generally used as a ‘hint/helper’ to the compiler that this variable will be non-null BUT isn’t getting set at construction time.
Very commonly used with DI frameworks so can define the dependency as non-null BUT it gets defined later.
What you’re doing is not a good candidate for lateinit IMO. If the consumer of the library needs to pass it, make the variable non-null, check it, and throw your exception.
If it is null, then after the !null check, you can reference it as non-null.A Gamal
01/09/2019, 12:46 PMsetter
method.
Hence, I prefer using delegates in this case, in which I could define that this method not accepting nullable object and could throw custom exception in case some other methods are called before init that object.Mike
01/09/2019, 12:48 PMlateinit
is the way to ‘solve’ it. Are you worried about interop with Java? I must assume so as otherwise you wouldn’t need to ‘jump through hoops’.
I would suggest EITHER taking a null as the parameter, and doing null checking in Kotlin with custom exception (as you want a custom exception) OR annotate with @Nonnull annotations, and let consumers know they must pay attention.Mike
01/09/2019, 12:50 PMlateinit
on a function parameter? That’s not clear, so I may be completely off here.A Gamal
01/09/2019, 12:52 PMDelegates.notNullOrException
as extension function, so I could do something like that private var config: Config by Delegates.notNullOrException(errorMessage = "configurations must be set")