Search code examples
springnhibernatekotlindata-class

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?


Solution

  • 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.)