1

I have an object

class Person {
@JsonProperty("name")
var name: String? = null

@JsonProperty("id")
lateinit var id: String}

There is an only empty constructor and I want to create a person so I wrote:

 val person = Person()
 person.name = "someName"
 person.id = "SomeId"

I'm pretty sure that there is a prettier syntax, something like

val person = Person {name = "someName" , id = "someId"}

but I can't find an example. am I missing something? should I create a secondary constructor to use this syntax or is there another way?

2 Answers 2

3

Please check apply method.

Your code will be like this:

val person = Person().apply {name = "someName", id = "someId"}

Another way - you can change declaration of Person to (e.g. just change brackets, replace var to val and remove lateinit):

class Person (@JsonProperty("name") val name: String? = null,
              @JsonProperty("id") val id: String )

Then you will able to do this:

val person = Person(name = "someName", id = "someId")
Sign up to request clarification or add additional context in comments.

Comments

0

You can achieve it with the constructor parameter.

class Person(
        @JsonProperty("name")
        var name: String? = null,
        @JsonProperty("id")
        var id: String
)



val person = Person(name = "someName", id = "someId")

Another way is make your class and desired variables open to be overridden.

open class Person {
    @JsonProperty("name")
    open var name: String? = null
    @JsonProperty("id")
    open var id: String = ""
}

val person =  object : Person() {
        override var name: String? = "SomeName"
        override var id = "SomeId"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.