https://kotlinlang.org logo
#codereview
Title
# codereview
c

christophsturm

03/05/2021, 4:24 PM
is there a way to get this to work without specifying the generic type:
Copy code
import kotlin.reflect.KClass

class Creator<T:Any>(val clazz: KClass<T>) {
    fun create(entity: T) {}
}

data class Post(val name:String)

class Transaction



inline fun <reified T:Any>Transaction.getCreator(): Creator<T> = Creator(T::class)

// this works:
Transaction().getCreator<Post>().create(Post("name"))
// this does not:
Transaction().getCreator().create(Post("name"))
i wonder if i can somehow help the compiler figure out that the generic type must be <Post> for the last line to work.
u

uli

03/06/2021, 11:57 PM
Only thing I can think of:
Copy code
inline fun <reified T:Any>
Transaction.create(entity:T): Creator<T> = Creator(T::class).create(entity)

Transaction().create(Post("name"))