Kotlin-当前实例的返回类型 [英] Kotlin - return type of current instance

查看:86
本文介绍了Kotlin-当前实例的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在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-当前实例的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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