Is there a way to use the default value on a non-optional parameter when null is passed?

前端 未结 2 1594
孤城傲影
孤城傲影 2021-02-04 23:44

For example, if I have the following data class:

data class Data(
    val name: String = \"\",
    val number: Long = 0
)

And functions that ca

2条回答
  •  离开以前
    2021-02-05 00:28

    You can define a companion object for your data class and overload its invoke operator to use default values when null is passed:

    data class Data private constructor(
        val name: String,
        val number: Long
    ) {
        companion object {
            operator fun invoke(
                name: String? = null,
                number: Long? = null
            ) = Data(
                name ?: "",
                number ?: 0
            )
        }
    }
    

提交回复
热议问题