我正在 Kotlin 中实现 vars,它可以接收来自某些用户的越界输入。我希望能够选择性地调用(仅在来自这些不受信任的用户的输入上)可以返回 null 的验证构造函数,然后在输入无效的情况下使用 Elvis 运算符指定默认值,如:var myFoo = Foo.fromInt(i) ?: 1
.我目前正在使用伴随对象方法来验证输入:
open class Foo(val x:Int) { // relies on valid x in 1..3
companion object {
fun fromInt(x: Int): Foo? = if (x in 1..3) Foo(x) else null
}
}
class Bar(x:Int) : Foo(x)
fun main(args:Array<String>) {
println(Foo.fromInt(2)) // Foo(2)
println(Foo.fromInt(20)) // null
// println(Bar.fromInt(2))
// would like Bar(2) but as expected, companion isn't inherited
}
当我继承
Foo
,我知道我必须重新创建伴生对象。我尝试从抽象类继承同伴;但是,调用 Foo(x)
仍然指向 Foo
而不是 Bar
, 除非我覆盖 fromInt
在每个子类的同伴中。是否有更好或更多 Kotlin 惯用的方法来处理这种可以返回 null
的验证构造函数模式?而不是创建请求的对象?
最佳答案
您可以使用 init block 以及 require
.
open class Foo(val x:Int) {
init {
require(x in 1..3) {
"relies on valid x in 1..3"
}
}
}
class Bar(x:Int) : Foo(x)
示例运行:
>>> open class Foo(val x:Int) {
... init {
... require(x in 1..3) {
... "relies on valid x in 1..3"
... }
... }
... }
>>> class Bar(x:Int) : Foo(x)
>>> val b = Bar(3)
>>> val b = Bar(4)
java.lang.IllegalArgumentException: relies on valid x in 1..3
at Line_18$Foo.<init>(Line_18.kts:3)
at Line_19$Bar.<init>(Line_19.kts:1)
>>> b.x
res22: kotlin.Int = 3
关于validation - 如何在 Kotlin 中实现验证构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46874406/