Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

634
Vistas
How to instantiate class in Kotlin, if the class is parameter of function?

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 = ""
}
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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()
}
over 4 years ago · Santiago Trujillo Denunciar

0

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.
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda