例如,如果我有以下数据类:

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

以及可以返回null的函数:

fun newName(): String? {}

fun newNumber(): Long? {}

I know I can use the following to use the value of the functions if they are not null:

val newName = newName()
val newNumber = newNumber()

val data = Data(
        if (newName != null) newName else "",
        if (newNumber != null) newNumber else 0
)

But is there a way to just use the default value specified in the constructor of the Data class when the values are null?

我在文档中找不到任何东西,但我希望这样的东西能起作用:

val data = Data(newName()?, newNumber()?)

But that does not compile.

推荐答案

您可以为您的数据类定义companion object,将overload定义为invoke operator,以便在传递null时使用默认值:

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
        )
    }
}

Kotlin相关问答推荐

如何在使用Kotlin Coroutines时检测和记录何时出现背压

将文本与文本字段的内容对齐

使用另一个对象的列表创建对象

Kotlin:类型不匹配:推断的类型已运行,但应等待

Kotlin 复制列表中的项目以创建具有相同数据的不同对象的新列表

使用 Kotlin 的 Springboot 中缺少 ResponseEntity 正文属性

Kotlin 接口类型参数

内容更改后的 var 重新计算

如何在 Hibernate Panache 中进行部分搜索

Kotlin 条件格式字符串

异常传播如何在 CoroutineScope.async 上工作?

在 SplashActivity 中显示的 Firebase 应用内消息.如何在 MainActivity 中显示它?

如何为你的 Flutter 元素添加 Kotlin 支持?

DatabaseManager_Impl 不是抽象的,不会覆盖 RoomDatabase 中的抽象方法 clearAllTables()

无法在 kotlin android 中以编程方式禁用 EditText

Kotlin 顶级函数与对象函数

Kotlin:如何在活页夹中返回正在运行的服务实例?

如果 Maybe 完成,则从其他来源将 Maybe 转换为 Single

封闭 lambda 的隐式参数被shadowed

以Kotlin为单位的货币数据类型