- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 407字
- 2021-06-10 18:49:21
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:
- Vue 3移動Web開發(fā)與性能調(diào)優(yōu)實戰(zhàn)
- Learning NServiceBus(Second Edition)
- Facebook Application Development with Graph API Cookbook
- Spring 5企業(yè)級開發(fā)實戰(zhàn)
- C語言程序設(shè)計(第2 版)
- Java編程指南:基礎(chǔ)知識、類庫應(yīng)用及案例設(shè)計
- JavaScript+jQuery開發(fā)實戰(zhàn)
- R語言游戲數(shù)據(jù)分析與挖掘
- 精通搜索分析
- Java程序員面試算法寶典
- AutoCAD VBA參數(shù)化繪圖程序開發(fā)與實戰(zhàn)編碼
- 微服務(wù)從小白到專家:Spring Cloud和Kubernetes實戰(zhàn)
- C++20高級編程
- SQL Server 入門很輕松(微課超值版)
- SSH框架企業(yè)級應(yīng)用實戰(zhàn)