kotlinkotlin-null-safety

Kotlin-Null Safety


Well...the question is --> "Write a program to check for the null value of the variables x and y using 'Elvis' operator and '!!' operator. Need to complete the function nullable. It should return the length of the string if it is not null, otherwise -1"

fun nullable(nullableString: String?): Int {
   

}
fun main(args: Array<String>) {
   val str = readLine()!!
    var result = -100
    if(str=="null") {
        result = nullable(null)
    }else
        result = nullable(str)
    println(result)
}

Solution

  • fun nullable(nullableString: String?): Int {
      return nullableString?.length ?: -1
    }