-
Notifications
You must be signed in to change notification settings - Fork 24
Kotlin Basics: Defining and using Nullable values
Devrath edited this page Dec 31, 2023
·
3 revisions
Contents |
|---|
What is meant by Nullability |
Solution to Nullability |
How to create nullable types |
Can we print null |
Will, we never get a null pointer exception |
- Many times a value might not have anything in it and we call it nullable in a programming language π
- Null is used to describe a value that may or may not be there.
- Ex: we are trying to refer a file from a location and instead there actually no file present -> program here returns null here
- Null is also called a billion-dollar mistake in programming because due to this it has resulted in a lot of fixes and patches in programming that have cost a lot of money.
-
Kotlinhas a built-in system called nullable type. -
Nullable typesare those that allow you to usenullthat defineconstantor avariable. - If a variable is marked
non-nullthen it cannot be assigned with anullvalue, If we try we get acompile-timeerror.
val age : Int? = null- Now if we want to use the variable
agewe can but we need to use certain checks else the compiler will throw the error. - This compiler check will help you avoid the accidental breaking of code.
Yes we can print the null if we explicitly mention that a value can be nullable
private fun initiate() {
var valueOne : String = "FirstName"
var valueTwo : String? = null
println(valueTwo)
}OUTPUT:
nullYes we will get if we explicitly mention non-null
var valueFour : String? = null
if(valueFour!!.length==2){
println("Success")
}OUTPUT::
Exception in thread "main" java.lang.NullPointerException
at DemoNullable.initiate(DemoNullable.kt:13)
at DemoNullable.<init>(DemoNullable.kt:3)
at MainKt.main(main.kt:3)- So we should always prevent using the
!!in kotlin as much as possible.
