传递null时,是否可以在非可选参数上使用默认值? [英] Is there a way to use the default value on a non-optional parameter when null is passed?

查看:78
本文介绍了传递null时,是否可以在非可选参数上使用默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For example, if I have the following data class:

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

以及可以返回null的函数:

fun newName(): String? {}

fun newNumber(): Long? {}

我知道如果不是null,我可以使用以下内容来使用这些函数的值:

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
)

但是当值是null时,有没有办法只使用在Data类的构造函数中指定的默认值?

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

我在文档中找不到任何内容,但我希望这样的方法可以工作:

I could not find anything in the documentation, but I was hoping something like this would work:

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

但是那不能编译.

推荐答案

您可以创建辅助构造函数,在接收null时使用相同的默认值:

You can create a secondary constructor that uses the same default values when receiving null:

data class Data(
        val name: String = "",
        val number: Long = 0
) {
    constructor(
            name: String? = null,
            number: Long? = null
    ) : this(
            name ?: "",
            number ?: 0
    )
}

这篇关于传递null时,是否可以在非可选参数上使用默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆