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

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:

主站蜘蛛池模板: 德兴市| 临泉县| 鄱阳县| 色达县| 神农架林区| 肃宁县| 九龙城区| 大新县| 华安县| 石阡县| 吉木乃县| 民乐县| 翼城县| 安乡县| 额尔古纳市| 茌平县| 白河县| 蒲江县| 丹东市| 花莲市| 广灵县| 余庆县| 南川市| 宁海县| 伊春市| 辉南县| 汝城县| 广水市| 濮阳县| 绵竹市| 巴中市| 崇明县| 凌海市| 石泉县| 洛隆县| 棋牌| 枣庄市| 城口县| 叶城县| 志丹县| 砚山县|