How to instantiate an object using default constructor values ​​in Kotlin?

I have a data class with default values.

data class Project(
    val code: String,
    val name: String,
    val categories: List<String> = emptyList())

Java reflection cannot create an instance of a class if some values ​​are null. I get an exception

java.lang.IllegalArgumentException: Parameter specified as non-null is null: method Project.<init>, parameter categories

This is because the method java.lang.reflect.Constructor<T>.instantiateClassexpects non-null arguments.

I have type information, I have a constructor definition, but I'm not sure how to call the constructor to use the default values ​​(the values ​​come from the database, categoriesmaybe null), is there a way to achieve this in Kotlin?

+4
source share
3 answers

Kotlin Java, , , Kotlin , , , .

.

  • . , callBy , .

  • @JvmOverloads , Java.

    @JvmOverloads
    data class Project(
        val code: String,
        val name: String,
        val categories: List<String> = emptyList()
    )
    
+3

Kotlin:

, . , . ,

data class Bird (val name: String = "peacock", val gender: String = "male")

Bird(), Bird ( "" ) Bird (gender = "female" ).

, ? . ,

data class Project(val code: String,
                   val name: String,
                   val categories: List<String>?)

emptyList() . emptyList, , null , ,

val project = if(categories == null)
       {
          Project(code,name)
       }
       else
       {
          Project(code,name,categories)
       }

kotlin.

JAVA:

java, @Hotkey , , kotlin , .

, java, @JvmOverloads, , @Hotkey ,

data class Project @JvmOverloads constructor(val code: String,
                                             val name: String,
                                             val categories: List<String>? = emptyList())
-1
source

Source: https://habr.com/ru/post/1685768/


All Articles