Tutorial by Examples

Normal types, like String, are not nullable. To make them able to hold null values, you have to explicitly denote that by putting a ? behind them: String? var string : String = "Hello World!" var nullableString: String? = null string = nullableString // Compiler error: Can't...
To access functions and properties of nullable types, you have to use special operators. The first one, ?., gives you the property or function you're trying to access, or it gives you null if the object is null: val string: String? = "Hello World!" print(string.length) // Compile erro...
If the compiler can infer that an object can't be null at a certain point, you don't have to use the special operators anymore: var string: String? = "Hello!" print(string.length) // Compile error if(string != null) { // The compiler now knows that string can't be null print(...
Sometimes we need to change type from Collection<T?> to Collections<T>. In that case, filterNotNull is our solution. val a: List<Int?> = listOf(1, 2, 3, null) val b: List<Int> = a.filterNotNull()
Sometimes it is desirable to evaluate a nullable expression in an if-else fashion. The elvis operator, ?:, can be used in Kotlin for such a situation. For instance: val value: String = data?.first() ?: "Nothing here." The expression above returns "Nothing here" if data?.firs...
!! suffixes ignore nullability and returns a non-null version of that type. KotlinNullPointerException will be thrown if the object is a null. val message: String? = null println(message!!) //KotlinNullPointerException thrown, app crashes
In Kotlin, we can declare variable which can hold null reference. Suppose we have a nullable reference a, we can say "if a is not null, use it, otherwise use some non-null value x" var a: String? = "Nullable String Value" Now, a can be null. So when we need to access value o...

Page 1 of 1