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?).

2

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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)
That's true - the isInitialized check is neater - but you won't be able to use lateinit with primitives, as in your example.
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: stackoverflow.com/a/45285841/4465208 - point is, there's a lot to pick from :)
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 ?

1 Comment

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
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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.