7

In Java one can initialize a reference variable with null, for example a String variable can be initialized like so:

String str = null;

But in Kotlin, the point is to avoid using null as much as possible. So how can I initialize a property without using null

var str: String = ...
2
  • Use a non-null String value? Commented Jun 26, 2017 at 17:40
  • You can use lateinit var and by lazy { ... } to define a property which is only later initialized with a not null value. See: stackoverflow.com/questions/36623177/… Commented Jun 26, 2017 at 17:44

4 Answers 4

6

user lateinit keywords.Need to use, and then initialize

private lateinit var str : String
fun myInit(){
    str = "something";
}

Note : that accessing the uninitialized lateinit property results in an UninitializedPropertyAccessException.

However, lateinit does not support basic data types, such as Int.

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

Comments

5

The point in Kotlin isn't to never use null (and nullable types), but rather to use it safely with convenient language constructs instead of fearing it. While using non-nullable types as much as possible is ideal, you don't have to always avoid them, that's why the various null handling constructs (safe calls, the Elvis operator, etc) exist.

If you can delay creating your variable until you have something to assign to it, that's a solution. If you can't, then marking it nullable and assigning null to it is perfectly fine, because the compiler will protect you from doing dangerous things with it.

Comments

1

you can do

var str: String

...

str = "Some Awesome Value"

if you want it nullable you can do

var str: String?

1 Comment

xtra credit for using the word "Awesome" in your code.
0

As an option:

var str: String by Delegates.NotNull()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.