0

Is there any way to annotate variable in Kotlin which is null on application start and after it is created it cannot be assigned to null again?

I can't set field as e.g. var someField: Boolean? because it can be nulled at some point or lateinit var someField: Boolean because it is expected that field is initialized before it will be used (or maybe this is proper way to resolve my situation?).

Zoe
  • 27,060
  • 21
  • 118
  • 148
user3626048
  • 706
  • 4
  • 19
  • 52

4 Answers4

3

I'm not sure I understand why lateinit doesn't work for you, other than that it doesn't work for primitive types - but the notNull delegate might be what you're looking for:

class X {
    var z: String by Delegates.notNull()
}

val x1 = X()
x1.z = "foo"
println(x1.z) // foo

val x2 = X()
println(x2.z) // IllegalStateException: Property z should be initialized before get.

It will give you an exception if you read it before setting it, and otherwise the property will have a non-null type.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • It looks interesting but i don't think catching an exception when trying to use variable is the best way. Checking ```isInitialized``` mentioned by @JBNizet looks like better solution (in this case) – user3626048 Jul 01 '18 at 09:58
  • That's true - the `isInitialized` check is neater - but you won't be able to use `lateinit` with primitives, as in your example. – zsmb13 Jul 01 '18 at 10:06
  • 1
    Also, perhaps your own delegate that might return `null` values but can't be set to a `null` value would work for you, somewhat like here: https://stackoverflow.com/a/45285841/4465208 - point is, there's a lot to pick from :) – zsmb13 Jul 01 '18 at 10:09
1

I'm not sure because i don't really see what you want to do but why you don't create the var when you initialize it? So the var will never be null and you will not have to initiate it with null

If you really need this var in order to check if it's null to change it why you don't use an int instead of a bool ?

Drping
  • 53
  • 12
  • my var is actually a field in class, I just gave shorted example. in my code var is a complex object, and at some point of code it is initialized but not always just after start of application – user3626048 Jul 01 '18 at 09:53
0

Declare it with latenit: lateinit var someField: Boolean
and after you assign a non-null value, use it like this someField!!
With this annotation you are saying to the compiler that somefield is not null, but it's your responsibility to keep it non-null.

0

When using a more complex type than Boolean, you should consider implementing a Null-Value-Pattern around it. Kotlin offers a neat structure for such a usecase:

sealed class Base

object NotInitialized : Base()

class Initialized : Base()

Like this you wouldn't run into any nullability issues. Also you can define a default directly with your implementation.

tynn
  • 38,113
  • 8
  • 108
  • 143