-
Notifications
You must be signed in to change notification settings - Fork 23
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.
-
Kotlin
has a built-in system called nullable type. -
Nullable types
are those that allow you to usenull
that defineconstant
or avariable
. - If a variable is marked
non-null
then it cannot be assigned with anull
value, If we try we get acompile-time
error.
val age : Int? = null
- Now if we want to use the variable
age
we 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:
null
Yes 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.