Do we need to initialize nullable fields in kotlin?

kotlin check if null
kotlin when statement null
kotlin if let
kotlin double exclamation mark
kotlin set property if not null
kotlin if not null vs let
kotlin add to map if not null
kotlin list add if not null

I have recently reviewed some kotlin codes, All nullable field initialized as null.

What is the difference between val x : String? = null and val x : String?

Should we initialize the nullable fields as null?

Everything, even nullable variables and primitives, need to be initialized in Kotlin. You can, as tynn mentioned, mark them as abstract if you require overriding. If you have an interface, however, you don't have to initialize them. This won't compile:

class Whatever {
    private var x: String? 
}

but this will:

interface IWhatever {
    protected var x: String?
}

This too:

abstract class Whatever {
    protected abstract var x: String?
}

If it's declared in a method, you don't have to initialize it directly, as long as it's initialized before it's accessed. This is the exactly same as in Java, if you're familiar with it.

If you don't initialize it in the constructor, you need to use lateinit. Or, if you have a val, you can override get:

val something: String?
    get() = "Some fallback. This doesn't need initialization because the getter is overridden, but if you use a different field here, you naturally need to initialize that"

As I opened with, even nullable variables need to be initialized. This is the way Kotlin is designed, and there's no way around that. So yes, you need to explicitly initialize the String as null, if you don't initialize it with something else right away.

Nullable Types and Null Safety in Kotlin, should be used for working with it;; Other issues caused by external Java To allow nulls, we can declare a variable as nullable string, written String? val which has a backing field and is not overridable), because otherwise  Kotlin's type system is aimed to eliminate NullPointerException 's from our code. The only possible causes of NPE's may be: Other issues caused by external Java code. In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that can not (non-null references).

val x : String? will create an uninitialized variable or property, depending on where it's defined. If it's in a class (rather than a function), it creates a property, and you cannot create an uninitalized property unless it's abstract. For example take this code:

class MyClass {
    val x : String?
}

This won't compile. You'll get Property must be initialized or be abstract.

This code, however, will compile

class MyClass {
    fun test() {
        val x : String?
    }
}

However it's a bit pointless as you will not be able to refer to that variable: as soon as you do you'll get Variable 'x' must be initialized.

So yes, generally when defining a nullable member you should initialize it (e.g. with a value of null), unless it's abstract, in which case the overriding class should initialize it.

Safe calls(?.) vs Null checks(!!) in Kotlin · Suneet Agrawal, Kotlin by default forces to initialize every object with a value and that However, we can make a nullable type object, by explicitly informing or Not Null Assertion !! operators have to be used to access the nullable variable. We can write x!!, and this will return a non-null value of x or throw an NPE if x is null. Kotlin’s requireNotNull() vs Not Null Assertion !! Kotlin provides two methods to call nullable type

A property must be initialized. Therefore you have to do the initialization var x : String? = null. Not assigning a value is only the declaration of the property and thus you'd have to make it abstract abstract val x : String?.

Alternatively you can use lateinit, also on non-nullable types. But this has the effect, that it's not null, but uninitialized lateinit var x : String.

Return null from fun in kotlin, Initialize a Non-nullable Variable. In Kotlin, we have to define upfront if our variable is nullable or not. This would aid the compiler flag potential null object being  We know that NullPointerException occurs when we try to call a method or access a property on a variable which is null. Kotlin disallows method calls and property access on nullable variables and thereby prevents many possible NullPointerExceptions.

Kotlin Null Safety, There are perfectly appropriate safe uses of null in Kotlin. null. If you need a way to represent whether a value is initialized or whether it Using a nullable field is much more concise in your definition than a sealed class. 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.

Null Safety, If you use it before you initialize it, you'll get a kotlin. visibility as the property, so the backing field can still be set to null from Java. lazy is a handy way to defer initializing a variable until you need it. GSON uses the magic sun.misc.Unsafe class which has an allocateInstance method which is obviously considered very unsafe because what it does is skip initialization (constructors/field initializers and the like) and security checks. So there is your answer why a Kotlin non-nullable field can be null.

The different ways to handle Nullable type in Kotlin, Kotlin provides comprehensive, native handling of nullable fields We cannot assign null to the reference a, and if you try to, it will cause a compiler error. When we want to access the b reference, we must handle the null  The modifier can be used on var properties declared inside the body of a class (not in the primary constructor, and only when the property does not have a custom getter or setter) and, since Kotlin 1.2, for top-level properties and local variables.