我该如何处理这个 "which is not a subtype of overridden" 错误

How can I handle this "which is not a subtype of overridden" error

我正在尝试用 Kotlin 编写一些可验证的表单界面。在验证部分,我使用 https://github.com/kamedon/Validation.

这是我正在尝试的非常简单的代码 运行;

import com.kamedon.validation.Validation


abstract class Validatable {
    abstract val validation: Validation<Any>

    fun validate() = validation.validate(this)
}

class LoginForm : Validatable() {
    val name: String = "Onur"
    val age: Int = 23

    override val validation = Validation<LoginForm> {
        "name" {
            be { name.length >= 5 } not "5 characters or more"
            be { name.length <= 10 } not "10 characters or less"
        }
        "age" {
            be { age >= 20 } not "Over 20 years old"
        }
    }
}


fun main(args: Array<String>) {
    val user = LoginForm()
    val result = user.validate()
    println(result)
}

这段代码给我;

Type of 'validation' is not a subtype of the overridden property 'public abstract val validation: Validation<Any> defined in Validatable'

如果我在 Validatable 中使用 Validation<out Any>,它会说;

Kotlin: Out-projected type 'Validation<out Any>' prohibits the use of 'public final fun validate(value: T): Map<String, List<String>> defined in com.kamedon.validation.Validation'

如果我在 Validatable 中使用 Validation<in Any>,它会说;

Kotlin: Type of 'validation' is not a subtype of the overridden property 'public abstract val validation: Validation<in Any> defined in Validatable'

如果我在 LoginForm 中使用 Validation<Any> 而不是 Validation<LoginForm>,代码 运行s 但是这次 validation 中的姓名和年龄是从 class 在其内部。我不想在库的使用方面改变这一点。

是否可以同时使用 inout 关键字,或者是否有其他方法可以实现我的目标。

您可以使抽象 class Validatable 成为通用的 class,并使子class 提供一个同时公开 Validation 对象的对象, 并且本身作为 target 来验证,例如

abstract class Validatable<T> {
    protected class ValidationInfo<T>(val target: T, val validation: Validation<T>)

    protected abstract val validationInfo: ValidationInfo<T>

    fun validate() = validationInfo.let { it.validation.validate(it.target) }
}

class LoginForm : Validatable<LoginForm>() {
    val name: String = "Onur"
    val age: Int = 23

    override val validationInfo = ValidationInfo(this, Validation {
        "name" {
            be { name.length >= 5 } not "5 characters or more"
            be { name.length <= 10 } not "10 characters or less"
        }
        "age" {
            be { age >= 20 } not "Over 20 years old"
        }
    })
}