Kotlin中可否决委托的空检查
我需要验证以YYMMDD格式显示生日的特定字符串。 我在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
数据类中执行此操作的方式是:
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)
})