官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 鄂州市| 上犹县| 惠水县| 肇庆市| 垫江县| 郯城县| 广宗县| 青神县| 张家港市| 甘孜| 高安市| 绵竹市| 建德市| 绥宁县| 丹东市| 通许县| 云龙县| 阜南县| 古蔺县| 镇原县| 新昌县| 奇台县| 阿荣旗| 闽清县| 嘉善县| 于都县| 论坛| 武城县| 广饶县| 清丰县| 保山市| 乃东县| 昭觉县| 高台县| 渭源县| 资兴市| 宁乡县| 夹江县| 古田县| 黄大仙区| 清镇市|