Kotlin数据类可选变量 [英] Kotlin data class optional variable

查看:291
本文介绍了Kotlin数据类可选变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

data class Student(
    val id: Int?,
    val firstName: String?,
    val lastName: String?,
    val hobbyId: Int?,
    val address1: String?,
    val address2: String?,
    val created: String?,
    val updated: String?,
    ...
)

我喜欢上面的数据类,并且我想创建一个只有名字和姓氏的Student实例. 所以如果我运行这个,

I have like above data class, and I want to create a Student instance with only first name and last name. So If I run this,

// creating a student 
Student(
    firstName = "Mark"
    lastName = "S"
)

我将得到没有传递参数'id'的值... 错误.

为避免这种情况,我像这样修改了Student类,

To avoid that, I modified the Student class like this,

data class Student(
    val id: Int? = null,
    val firstName: String? = null,
    val lastName: String? = null,
    val hobbyId: Int? = null,
    val address1: String? = null,
    val address2: String? = null,
    val created: String? = null,
    val updated: String? = null,
    ...
)

但是看起来很丑.

还有什么更好的方法吗?

Is there any better way?

推荐答案

我不确定我提供给您的解决方案是否最佳.但是绝对整洁.

I am not sure the solution I am giving you is the best or not. But definitely neat.

我唯一不喜欢将null用作默认参数的原因是,因为Kotlin提供了Null Safety,所以不要仅仅因为满足其他要求而将其删除.仅当它们可以为null时,才将它们标记为null.其他旧的Java方式也不错.用一些默认值初始化它们.

The only thing I don't like to go with nulls as default param, because Kotlin offers Null Safety, lets not remove it just because to fulfil some other requirement. Mark them null only if they can be null. Else old Java way is good. Initialize them with some default value.

data class Student(val id: Int,
                   val firstName: String,
                   val lastName: String,
                   val hobbyId: Int,
                   val address1: String,
                   val address2: String,
                   val created: String,
                   val updated: String) {
    constructor(firstName: String, lastName: String) :
            this(Int.MIN_VALUE, firstName, lastName, Int.MIN_VALUE, "", "", "", "")
}

这篇关于Kotlin数据类可选变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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