简体   繁体   English

Kotlin-Null 安全性

[英]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 '!!'嗯...问题是 --> “编写一个程序来检查变量 x 和 y 的空值,使用 'Elvis' 运算符和 '!!' operator. Need to complete the function nullable. It should return the length of the string if it is not null, otherwise -1"运算符。需要完成可空函数。如果不为空则返回字符串的长度,否则返回-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)
}
fun nullable(nullableString: String?): Int {
  return nullableString?.length ?: -1
}

基本上只需使用Elvis运算符返回输入长度,如果输入为null ,则返回-1

fun nullable(nullableString: String?): Int = nullableString?.length ?: -1
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这里 'str' 变量接受值,而默认值为 -1 它返回默认值 -1 或 int 值,这是使用 Elvis 运算符但你想要长度而不是值所以这里是解决方案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM