https://kotlinlang.org logo
#getting-started
Title
# getting-started
t

Tomas Kormanak

03/30/2022, 9:34 AM
Hi, is there a way to define private setter for property defined in constructor param? I need something like this, but because of
@Seriazlizable
annotation constructor can not have parameter which is not property
Copy code
@Serializable
class Document(
    name: String,
) {
    var name: String = name
        private set
}
s

Stephan Schroeder

03/30/2022, 3:04 PM
your class compiles for me and looks good. What fails?
k

Klitos Kyriacou

03/30/2022, 3:09 PM
kotlinx.serialization requires primary constructor to parameters to be properties. It compiles, but it won't serialize automatically.
e

ephemient

03/30/2022, 4:58 PM
not as far as I know, but you can
Copy code
@Serializable
class Document(
    @SerialName("name")
    private var _name: String,
) {
    val name: String
        get() = _name
}
this might work too,
Copy code
@Serializable
class Document private constructor(
) {
    constructor(
        name: String,
    ) : this(
    ) {
        this.name = name
    }

    var name: String = ""
        private set
but unfortunately both do have some effect on the public API of your class
4 Views