The nullable type

In Kotlin, we can declare a variable to hold a null value using the nullable type.

Let's write a program to check whether the given input is Web. If it is, it should return Web Development. If not, it should return an empty string.

Consider the code for 11_NullType.kts:

fun checkInput (data: String) : String {
if(data == "Web")
return "Web development"
return ""
}
println(checkInput ("Web"))
println(checkInput ("Android"))

The output is as follows:

So far, so good. Let's say that we want to return null if there is no match for the given input:

fun checkInput (data: String) : String {
if(data == "Web")
return "Web development"
return null
}
println(checkInput ("Web"))
println(checkInput ("Android"))

Let's compile and run this code:

Here, we get a compilation error because the return type is non-null by default in the function declaration. If we want to return null, we have to specify the type as nullable using ?:

fun checkInput (data: String) : String? {
if(data == "Web")
return "Web development"
return null
}
println(checkInput ("Web"))
println(checkInput ("Android"))

The output is as follows:

This code has compiled and run successfully. When we invoke the checkInput function with Web, it prints Web development. When we pass Android, it prints null to the console.

Similarly, when we receive data in response, we can also receive a nullable type from the function and perform a null check. Kotlin provides a very elegant syntax to do null checks.

Consider the code for 11a_NullCheck.kts:

fun checkInput (data: String) : String? {
if(data == "Web")
return "Web development"
return null
}
var response = checkInput ("Web")
println(response)
response ?.let {
println("got non null value")
} ?: run {
println("got null")
}

The checkInput() function returns a string if there is a match for Web, otherwise it returns null. Once the function returns a value, we can check whether it is null or non-null and act appropriately. ?.let and ?:run are used for this kind of scenario.

The output is as follows:

Consider the code for 11a_NullCheck.kts:

fun checkInput (data: String) : String? {
if(data == "Web")
return "Web development"
return null
}
var response = checkInput ("iOS")
println(response)
response ?.let {
println("got non null value")
} ?: run {
println("got null")
}

We now pass iOS instead of Web.

In this case, the output is as follows:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset