问题描述
我正在Kotlin中建立一个验证库.基类是abstract
,它实现适用于所有类型的方法. isNotNull
例如:
I am building a validation library in Kotlin. The base class is abstract
and implements methods that apply to all types; isNotNull
for example:
abstract class Validator<V>(protected val value: V?) {
fun isNotNull(): Validator<V> {
if(value == null) {
// ... some validation handling here ...
}
return this
}
}
然后我为特定类型的验证器分类:
Then I am sub-classing validators for specific types:
class IntValidator(value: Int?) : Validator<Int>(value) {
fun isNotZero(): IntValidator {
if(value == 0) {
// ... some validation handling here ...
}
return this
}
}
现在说我想验证一个Int吗?不为空且不为零
Now say I want to validate that an Int? is not null and not zero
val validator = IntValidator(myNullableInteger)
validator
.isNotNull()
.isNotZero()
上面的代码不起作用,因为.isNotNull()
返回的是Validator<V>
,而不是IntValidator
,因此.isNotZero()
不在范围内.
The code above does not work, because .isNotNull()
returns Validator<V>
, rather than IntValidator
, so .isNotZero()
is no longer in scope.
方法是否可以返回实例化它们的类型(在我的情况下,我希望它返回IntValidator
而不是Validator<T>
)?
Is there a way for methods to return the type that instantiated them (in my case, I want it to return IntValidator
, not Validator<T>
)?
推荐答案
也许您应该重新考虑API设计.不链接方法而是使用范围函数呢?
Maybe you should reconsider the API design. What about not chaining the methods and using scope functions instead?
val validator = IntValidator(myNullableInteger)
with(validator) {
isNotNull()
isNotZero()
}
在IntValidator
的范围内,两种方法都可以访问.
In the scope of an IntValidator
, both methods will be accessible.
这篇关于Kotlin-当前实例的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!