【问题标题】:null check for vetoable delegates in Kotlin在 Kotlin 中对可否决的代表进行空检查
【发布时间】: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


    【解决方案1】:

    你可以简单地使用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)
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-10
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      相关资源
      最近更新 更多