How do I process the arguments of the secondary constructor to make them unchangeable property values?

Asked 2 years ago, Updated 2 years ago, 77 views

I think the only thing I can do is initialize the unalterable properties through the primary constructor, but I'm having trouble with how to call the primary constructor using the results calculated by the secondary constructor.

Consider, for example, the class Person with the property name and two constructors.I would like longName to be space separated on the secondary constructor and set it to the value of name, but I cannot pass the calculated string because the variable in the code block is not available on the primary constructor call (this.

class Person (val name: String) {
    constructor(vararg longName:String)/*:this(sj.toString())*/{
        valsj=java.util.StringJoiner("")
        longName.forEach {sj.add(it)}
    }
}

How do I define a class like Person?

kotlin

2022-09-30 17:04

1 Answers

How about the following?

class Person {

    val name —String

    constructor(name:String){
        this.name = name
    }

    constructor(vararg longName:String) {
        name = longName.joinToString("")
    }
}

In this case, I think the following is more concise.

class Person (val name: String) {

    constructor(vararg longName:String):
            This(longName.joinToString(""))
}

Other than that,

class Person (val name: String) {

    private company object {
        fundoSomething(vararg longName:String): String {
            // Long processing...
            return longName.joinToString("")
        }
    }

    constructor(vararg longName: String): this(doSomething(*longName))
}


2022-09-30 17:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.