我可以在Kotlin中初始化对象并在一行中设置参数吗

时间:2018-08-14 00:30:05

标签: kotlin

班级:

class CameraBrandDto(override val id: Long = 0, override var dateCreated: Date = Date(), override var dateUpdated: Date = Date()) : DataTransportObject {
    override var clazz = this.javaClass.simpleName.replace("Dto", "")

    @NotBlank
    @Size(max = 13)
    var name: String = ""

    var models: MutableSet<DtoMin> = mutableSetOf(DtoMin(0, "UNDEFINED", "UNDEFINED", Date(), Date()))

}

我想一行完成

val axisDto  = CameraBrandDto()
axisDto.name = "AXIS"

这可能吗?

1 个答案:

答案 0 :(得分:6)

是的,只需使用标准库函数.apply { ... },该函数对对象执行the lambda with receiver并返回该对象:

val axisDto = CameraBrandDto().apply { name = "AXIS" }