Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use extension properties in Kotlin as constants?

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?

like image 810
Artyom Karnov Avatar asked Jan 28 '23 09:01

Artyom Karnov


1 Answers

If you really want to use String.EMPTY, you can create an extension property on String's companion object:

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

Usage in this case is just like you've shown:

val firstName: String = String.EMPTY

(This is mentioned in the official documentation here.)

like image 90
zsmb13 Avatar answered Jan 31 '23 07:01

zsmb13