-
Notifications
You must be signed in to change notification settings - Fork 22
Kotlin Basics: Defining and using Nullable values
Devrath edited this page Dec 31, 2023
·
3 revisions
![Screenshot 2023-12-24 at 9 34 13β―AM](https://private-user-images.githubusercontent.com/1456191/292654314-dba74875-7855-4762-9695-ae306f37ef8e.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MjQ2MTcwMTgsIm5iZiI6MTcyNDYxNjcxOCwicGF0aCI6Ii8xNDU2MTkxLzI5MjY1NDMxNC1kYmE3NDg3NS03ODU1LTQ3NjItOTY5NS1hZTMwNmYzN2VmOGUucG5nP1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9QUtJQVZDT0RZTFNBNTNQUUs0WkElMkYyMDI0MDgyNSUyRnVzLWVhc3QtMSUyRnMzJTJGYXdzNF9yZXF1ZXN0JlgtQW16LURhdGU9MjAyNDA4MjVUMjAxMTU4WiZYLUFtei1FeHBpcmVzPTMwMCZYLUFtei1TaWduYXR1cmU9NDA3NDYxYWJjYTlhZTlhNjY0ZThiZjZjZDM3ODc3YTRkYmM3M2UwNDFkODcxMTAyNmE0MTIwNmNjYmY2ODRjNCZYLUFtei1TaWduZWRIZWFkZXJzPWhvc3QmYWN0b3JfaWQ9MCZrZXlfaWQ9MCZyZXBvX2lkPTAifQ.85XUUG4XGDVplshk9ooAHUloCTt_4DthVOhaAm9P8zg)
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.