如何在Kotlin中强制使用空的非null字符串? [英] How to enforce an empty, non-null String in Kotlin?

查看:426
本文介绍了如何在Kotlin中强制使用空的非null字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常想保留一个不能为空的字符串或空白-空格不够好.编译器很好地处理了String?以防止为null,我们可以使用aNullableString.isNullOrBlank()来检查它是否为null或为空.但是,这要求在使用空白支票的任何地方都要对其进行处理,如果空白支票是空白的,则要处理错误,如果错过一个斑点,这可能会导致意外错误.

I often want to hold a string that can not be null or blank - whitespace isn't good enough. The compiler handles String? nicely to prevent null, and we can use aNullableString.isNullOrBlank() to check if it is null or blank. However, this requires that the blank check be handled everywhere it is used then handle errors if it is blank, which can cause unexpected errors if you miss a spot.

是否有更简单的方法来定义String的类型或扩展名,以强制字符串不能为空?

Is there an easier way to define a type or extension to String that will enforce that the string must not be blank?

推荐答案

如果您在多个地方都需要此行为,则可以创建一个委托来处理它,在其中可以在private属性的设置器中进行检查,或在setValue函数中:

If you need this behavior in multiple places, you can create a delegate to handle it, where you can do the check either in the setter of the private property, or in the setValue function:

class NonEmptyString(private var str: String) {
    init {
        if (str.isEmpty()) {
            throw IllegalArgumentException("Invalid initial value")
        }
    }

    operator fun getValue(thisRef: Any?, property: KProperty<*>) = str

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        if (value.isEmpty()) {
            return // or throw or something
        }
        str = value
    }
}

其用法如下:

var nonEmpty by NonEmptyString("something")
nonEmpty = ""
println(nonEmpty) // "something"

这篇关于如何在Kotlin中强制使用空的非null字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆