- 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:
- Hands-On Machine Learning with scikit:learn and Scientific Python Toolkits
- OpenCV實(shí)例精解
- PostgreSQL技術(shù)內(nèi)幕:事務(wù)處理深度探索
- Servlet/JSP深入詳解
- Java程序設(shè)計(jì)與實(shí)踐教程(第2版)
- Internet of Things with Intel Galileo
- 從學(xué)徒到高手:汽車電路識(shí)圖、故障檢測(cè)與維修技能全圖解
- ArcGIS By Example
- Symfony2 Essentials
- C語言程序設(shè)計(jì)
- 51單片機(jī)C語言開發(fā)教程
- Learning AngularJS for .NET Developers
- C專家編程
- HTML5權(quán)威指南
- Hands-On Neural Network Programming with C#