Skip to content

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

What is meant by Nullability

  • 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.

Solution to Nullability

  • Kotlin has a built-in system called nullable type.
  • Nullable types are those that allow you to use null that define constant or a variable.
  • If a variable is marked non-null then it cannot be assigned with a null value, If we try we get a compile-time error.

How to create nullable types

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.

Can we print null

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

Will, we never get a null pointer exception

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.
Clone this wiki locally