Home > Software engineering >  Kotlin-Null Safety
Kotlin-Null Safety

Time:06-04

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)
}

CodePudding user response:

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

CodePudding user response:

Basically just return the input length using the Elvis operator or -1 if the input is null.

fun nullable(nullableString: String?): Int = nullableString?.length ?: -1

CodePudding user response:

fun nullable(nullableString: String?, default: Int): Int {
    return nullableString?.toIntOrNull() ?: default
}

fun main(args: Array<String>) {
    val str = readlnOrNull()
    val result = -1
    println(nullable(str, result))
}

Here 'str' variable accepts value while the default is -1 it returns default -1 or int value, this is with Elvis operator but you want length instead of value so here is the solution

fun nullable(nullableString: String?, default: Int): Int {
    return if (nullableString?.length == 0) {
        default
    } else { 
        nullableString?.length!! // !! is called the 'not-null assertion operator'
    }
}

fun main(args: Array<String>) {
    val str = readlnOrNull()
    val result = -1
    println(nullable(str, result))
}
  • Related