【发布时间】:2020-04-11 19:16:15
【问题描述】:
我需要验证一个 YYMMDD 格式的生日字符串。
我在data class 中的做法是:
val dateOfBirth: String by Delegates.vetoable(
text.split("\n")[1].substring(13, 19),
onChange = { _: KProperty<*>, _: String, newValue: String ->
"\\d{6}".toRegex().matches(newValue)
})
基本上,我的班级会使用某个 text 进行实例化,例如 val clz = MyClass(text = "")
但是,我正在编写一些测试,并且正在检查空字符串 "" 会发生什么,它会因
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
这是text.split("\n")[1].substring(13, 19) 所在的行,因为基本上,text 是空的。
在 Kotlin 中有没有办法避免或改进这种情况?在我的验证中,我假设 text 不是空的,但它可以是。
谢谢!
【问题讨论】:
标签: kotlin delegates delegation