Updated April 4, 2023
Introduction to Kotlin Null
Kotlin null is the type of reference value it must be the null or no value and that cannot be handled using the normal property values the variable that cannot hold the null value means it will throw the error in compile time so the kotlin neither allows null values to be passed as the argument nor allows the null object references unless it specifies the variable can be of null types the compiler allows and it knows the variable value can be of null and such variables are referred to as the nullable values in kotlin.
Syntax
In kotlin language, we used a lot of default classes, methods, and variables used to implement the application. For each variable, we specify the type like datatype to declare and pass the values based on the datatype. The null is the type of reference so it accepts only the nullable values.
fun main()
{
var variablename: datatype = values // It is the regular initialization it accepts non-null values by default
variablename = null // It shows the compilation error
}
The above codes are the basic syntax for declaring and initialize the null values in the variable.
How does null work in Kotlin?
The kotlin language has many types and it is aimed at eliminates the danger of the nullable variable reference. Many languages is triage to access the member of the null reference will result in the null reference exception. Like java language, this would be the equivalent of the NullPointerException as the cause of the kotlin language. We used “!!” operator and explicitly call and to throw the NullPointerException() in the application console. Generally, the data inconsistency is regarded for to initialize and uninitialized constructor using “this” keyword and passed the values. The superclass constructor calls the open type of member function whichever implemented in the derived class section and it uses the uninitialized state. The interoperation which attempts to access the member of the null reference of the platform type and nullability issues with generic types and it is being used for the java interoperation. It looks like the piece of code that might be added with the null values into the kotlin collections and other util packages based on the requirement. But rest of the things are caused by the external type of codes that distinguishes between the references and it can hold the nullable references and non-null values. Using conditional statements and loops used to iterate and validate the null values in the code.
Example #1
Code:
fun main(args: Array<String>) {
var str: String? = "Welcome To My Domain its the first example that related to the kotlin null concepts"
println(str)
if (str != null) {
println("The string value length is shown as ${str.length}")
} else {
println("The null strings are shown on the output console")
}
str = null
println(str)
if (str != null) {
println("The string value length is shown as ${str.length}")
} else {
println("The null strings are shown on the output console")
}
var str1: String? = "January is the first month,February is the second month, March is the third month, April is the fourth month, May is the fifth month, June is the sixth month, July is the seventh month, August is the eigth month, September is the ninth month, October is the tenth month, November is the eleventh month, December is the twelth month"
var str2: String? = null
println(str1?.toUpperCase())
println(str1?.length)
println(str2?.toUpperCase())
var str3: List<String?> = listOf("Anna nagar Mogapper Ambattur Avadi Koyambedu Ashok nagar Spencer Gopalapuram Poyes Garden","Valasaravakkam Maangadu Puzhal Central LIC Mount road Alandur Meenampakam Tirisulam Marina Beach Chepauk Egmore", null, "KK nagar", "Guindy", "Tambaram", "Maduravoyal","Mayilapur","Thiruvanmaiyur","Perungalathur oorapakam Vandaloor",null)
var str4 = listOf<String?>()
for (x in str3) {
x?.let { str4 = str4.plus(it) }
x?.also{it -> println(it)}
}
}
Output:
In the above example, we checked the null reference and collection list to validate the data.
Example #2
Code:
interface Second {
val x : Int
val y : String
get() = "Welcome To My Domain its the second example that related to the kotlin null"
fun demo1()
}
class secondClass : Second {
override val x : Int
get() = 54
override fun demo1()
{
println("Have a Nice Day users please try again")
}
}
class Example
{
var studName: String = ""
var studId: Int = 0
fun studDetails(str1: String, in1: Int) {
studName = str1
studId = in1
println("Please see the student name: $studName")
println("Please see the student id: $studId")
}
}
fun main(args: Array<String>) {
var a : String? = "Welcome To My Domain its the second example that related to the kotlin null"
println(a?.length)
a = null
println(a?.length ?: "-1")
var std1 = Example()
val stdset=setOf("Sivaraj",213,"Raman",342,"Siva",321)
for(i in stdset){
println(i)
}
std1.studDetails("Raman", 342)
println("studName of the new Example: ${std1.studName}")
val nul1 = setOf("TV" , "Laptop", "Computer")
val nul2 = setOf( 'T' , 'L' , 'C' )
for(i in nul1)
print( i )
println()
for(i in nul2)
print( i )
println()
}
Output:
In the second example, we used classes, and interfaces to implement the application with a null value reference.
Example #3
Code:
sealed class Hospital{
class TMF(var hspId: Float): Hospital()
class Appolo(var hspId: Int): Hospital()
class Kauvery(var hspId: Int, var hspgst: Int): Hospital()
}
fun demo(h: Hospital) =
when (h) {
is Hospital.TMF ->println("TMF surface area is ${1*h.hspId*h.hspId}")
is Hospital.Appolo ->println("Appolo surface area is ${h.hspId*h.hspId}")
is Hospital.Kauvery ->println("Kauvery surface area is ${h.hspId*h.hspgst}")
}
fun main(args: Array<String>) {
var a : String? = "Welcome To My Domain its the third example that related to the kotlin null"
println(a!!.length)
a = null
var TMF = Hospital.TMF(32.23f)
var Appolo = Hospital.Appolo(4)
var Kauvery = Hospital.Kauvery(6,8)
demo(TMF)
demo(Appolo)
demo(Kauvery)
}
Output:
In the final example, we validate the null check utilized with the sealed class.
Conclusion
In kotlin language, we used a lot of default classes, methods, and variables to implement the application, and based on the requirement we imported the packages and classes, methods will be called in the script. The null is the keyword and it is used to validate the variable values or another validation depends on the usage of null reference.
Recommended Articles
This is a guide to Kotlin Null. Here we discuss the introduction, syntax, and working of null in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –