3

Im trying to make universal function in Kotlin, which can instantiate every time different model classes. Class type is a parameter, to make instance from that class and fill it with data from Json object.

fun<T> foo() {
    var myModel = T()
    myModel.id = 2
    myModel.name = ""
}

2 Answers 2

8

You can use an inline reified function in combination with an interface.

With reified you can access the real class of the generic type parameter. You still not allowed to call the constructor directly, but reflection will work.

To assign the id and name, you need to define an interface, that all of your model classes are required to implement:

interface Model {
    var id: Int?
    var name: String?
}

inline fun <reified T : Model> createModel() : T {
    val myModel = T::class.createInstance()
    myModel.id = 2
    myModel.name = ""
    return myModel
}

A simple example:

class TestModel() :  Model {
    override var id: Int? = null
    override var name: String? = null
}

fun main() {
    val model: TestModel = createModel()
}
Sign up to request clarification or add additional context in comments.

1 Comment

What if class has no no-arg constructor?
2

You cannot use T definition itself, pass class to the function instead.

import kotlin.reflect.KClass

open class Model {
    var id: Int? = null
    var name: String? = null
    fun say() {
        println("hello.")
    }
}
class MyModel: Model()

fun<T: Model> foo(type: KClass<T>): T {
    val myModel = type.java.newInstance()
    myModel.id = 2
    myModel.name = ""
    return myModel
}

val mymodel = foo(MyModel::class)
mymodel.say() // hello.

2 Comments

This the "java" way. In Kotlin, we would rather use an inline function with reified type parameter as mentioned by @Rene
Thx! You and @Rene also help me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.