Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
Kotlin was designed to eliminate the null reference errors that are common in many languages, including Java. Null safety is one of Kotlin's most distinctive features. Let's dive into this topic:
In Kotlin, by default, variables cannot hold a null
value. To declare a variable as nullable, you use ?
after the type:
var name: String = "Alice" // name = null // This will cause a compile-time error var nullableName: String? = null // This is allowed
?.
):You can use the safe call operator to safely access a property or method on a nullable variable. If the variable is null
, the operation returns null
.
val length: Int? = nullableName?.length
?:
):The Elvis operator allows you to provide a default value if a nullable expression resolves to null
.
val len = nullableName?.length ?: 0
!!
):If you are certain that a nullable expression is non-null, you can use the !!
operator. However, if the expression is null
, it'll throw a NullPointerException
.
val lenAgain: Int = nullableName!!.length // Throws NullPointerException if nullableName is null
as?
):Kotlin provides a safe cast operator (as?
), which tries to cast a value to a specified type and returns null
if the cast is unsuccessful.
val anyValue: Any = 123 val stringValue: String? = anyValue as? String // This will be null, not a ClassCastException
null
in Conditions:You can check for null
values using the ==
and !=
operators.
if (nullableName != null) { println(nullableName.length) }
let
with Safe Calls:Using ?.let
is a common pattern to perform an operation on a non-null value of a nullable variable:
nullableName?.let { println("Name is $it and its length is ${it.length}") }
lateinit
:If you have a non-null property that is not initialized in the constructor but you promise to initialize it before using, you can use the lateinit
modifier. However, accessing it before initialization will throw an exception.
class Sample { lateinit var name: String fun initName() { name = "Kotlin" } }
null
in Collections:Kotlin differentiates between a list that can have null
elements and a list that cannot.
val listWithNulls: List<String?> = listOf("Kotlin", null, "Java") val listWithoutNulls: List<String> = listWithNulls.filterNotNull()
Kotlin's null safety features are designed to eliminate the risk of NullPointerException
in your code. By using Kotlin's type system effectively and understanding these features, you can write more robust and error-resistant code.
Nullable types in Kotlin:
?
to its type.var nullableString: String? = "Hello, Kotlin!"
Safe calls in Kotlin:
?.
) to access properties or call methods on nullable objects.val length: Int? = nullableString?.length
Elvis operator in Kotlin null safety:
?:
) to provide a default value if the expression is null.val lengthOrDefault: Int = nullableString?.length ?: 0
!! operator and non-null assertions in Kotlin:
!!
operator asserts that an expression is non-null, use with caution.val nonNullLength: Int = nullableString!!.length
The use of ?. in Kotlin null safety:
?.
operator is used for safe calls to avoid null pointer exceptions.val firstChar: Char? = nullableString?.get(0)
Checking for null with if and when statements in Kotlin:
if
or when
to explicitly check for null.if (nullableString != null) { // Code when not null } else { // Code when null }
Default values for nullable variables in Kotlin:
var nullableInt: Int? = null val nonNullInt: Int = nullableInt ?: 0
Smart casts and type checks in Kotlin null safety:
if (nullableString is String) { val length: Int = nullableString.length // Automatically cast to String }
Nullable collections in Kotlin:
val nullableList: List<String?> = listOf("one", null, "three")
Working with nullable types in Kotlin functions:
fun concatStrings(str1: String?, str2: String?): String? { return str1?.plus(str2) }
Null safety and Java interoperability in Kotlin:
val javaObject: JavaClass? = JavaClass() val length: Int? = javaObject?.getString()?.length