Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

630
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!