4

I have data class

data class User(
        @Id
        @GeneratedValue(strategy = GenerationType.SEQUENCE)
        val userId: Long = 0,

        @Column(nullable = false, unique = true)
        val email: String = "",

        @Column(nullable = false)
        val firstName: String = "",
)

I hate using "" for initialization. I would like use something like

 @Column(nullable = false)
 val firstName: String = String.EMPTY

I know about extension properties or functions, but they looks aren't so good as well

val firstName: String = "".empty()
val firstName: String = "".EMPTY

How do you write entity classes? Is there more elegant way?

4

1 回答 1

9

如果你真的想使用,你可以在的伴生对象String.EMPTY上创建一个扩展属性:String

val String.Companion.EMPTY: String
    get() = ""

这种情况下的用法就像你展示的那样:

val firstName: String = String.EMPTY

(这里的官方文档中提到了这一点。)

于 2018-09-27T18:10:25.007 回答