Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin中可否决委托的空检查_Kotlin_Delegates_Delegation - Fatal编程技术网

Kotlin中可否决委托的空检查

Kotlin中可否决委托的空检查,kotlin,delegates,delegation,Kotlin,Delegates,Delegation,我需要验证以YYMMDD格式显示生日的特定字符串。 我在数据类中执行此操作的方式是: val dateOfBirth: String by Delegates.vetoable( text.split("\n")[1].substring(13, 19), onChange = { _: KProperty<*>, _: String, newValue: String -> "\\d{6}".toRegex().matc

我需要验证以YYMMDD格式显示生日的特定字符串。 我在
数据类中执行此操作的方式是:

val dateOfBirth: String by Delegates.vetoable(
        text.split("\n")[1].substring(13, 19),
        onChange = { _: KProperty<*>, _: String, newValue: String ->
            "\\d{6}".toRegex().matches(newValue)
        })
这是
text.split(“\n”)[1]子字符串(13,19)
所在的行,因为基本上,
text
是空的

Kotlin有没有办法避免或改善这种情况?在我的验证中,我假设
文本
不是空的,但它可以是空的


谢谢

您可以简单地使用
if
检查字符串是否有足够的长度,并根据业务逻辑分配一些默认值/引发异常等

大概是这样的:

val dateOfBirth: String by Delegates.vetoable(
    if(text.length >= 19)
        text.split("\n")[1].substring(13, 19)
    else // Handle invalid text length
     "" ,
    onChange = { _: KProperty<*>, _: String, newValue: String ->
        "\\d{6}".toRegex().matches(newValue)
    })
val dateOfBirth:String by Delegates.vetoable(
如果(text.length>=19)
text.split(“\n”)[1]。子字符串(13,19)
else//处理无效的文本长度
"" ,
onChange={{}:KProperty,{:String,newValue:String->
“\\d{6}”.toRegex().matches(newValue)
})
val dateOfBirth: String by Delegates.vetoable(
    if(text.length >= 19)
        text.split("\n")[1].substring(13, 19)
    else // Handle invalid text length
     "" ,
    onChange = { _: KProperty<*>, _: String, newValue: String ->
        "\\d{6}".toRegex().matches(newValue)
    })