Kotlin:如何在主构造函数中使用自定义设置器

Kotlin: How to use custom setters in primary constructor

我不知道如何做到在创建对象时参数值“通过setters”我得到的最接近的是复制代码,使用一次在创建对象时再次在 setter

class User(var name: String, password: String, age: Int) {

    // IDK how use a custom setter in the primary constructor
    var password: String = if (password.length > 6) password else throw  IllegalArgumentException("Password is too short")
        set(value) {
            if(value.length > 6)
                field = value
            else
                throw IllegalArgumentException("Password is too short")
        }

    var age: Int = if (age > 18) age else throw IllegalArgumentException("Age must be 18+")
        set(value) {
            if(value > 18 )
                field = value
            else
                throw IllegalArgumentException("Age must be 18+")
        }

    override fun toString(): String {
        return "login: $name, password: $password, age: $age"
    }


}

fun main() {

    val user1 = User("User1", "swordfish", 20)
    println(user1)

    try{
        // This code throw a exception
        user1.password = "fish"
    }
    catch (e: IllegalArgumentException){
        println(e.message)
    }

    // Here we can see if password has changed
    println(user1)

    try{
        val user2 = User("U2", "swordfish", 2)
        println(user2)
    }
    catch (e: IllegalArgumentException){
        println(e.message)
    }
}

我想要的是能够检查(通过 setter)创建对象时传递的参数

可能有很多方法可以解决这个问题,但你没有错。

我要做的是使用内置 error() 函数在 JVM 上抛出 IllegalStateException

class User(var name: String, password: String, age: Int) {


    var password: String = password
        set(value) {
            assertValidPassword(value)
            field = value
        }

    var age: Int = age
       set(value) {
           assertValidAge(age)  
           field = value
       }

    init {
         this.password = password
         this.age =age
    }

    override fun toString(): String {
        return "login: $name, password: $password, age: $age"
    }
    private fun assertValidAge(age: Int) {
       if (age <=18 ) error("Age must be 18+")
    }
    private fun assertValidPassword(password: String) {
        if(password.length <= 6) error("Password is too short")
    }
}

我在这里做了什么:

  1. 我已将验证登录放在一个函数中,我可以在 setter 和构造函数主体中重复使用该函数
  2. 我通过指定 init {} 块添加了主构造函数体