Generic function works, but generic class doesn't?

72 Views Asked by At

I would like a class that is a generic for KProperty1, I can do this for a function, but not a class:

import kotlin.reflect.KProperty1

data class Dog(val name: String, val age: Int)

fun <P: KProperty1<*, *>> reflectionHelper(input: P) = input.name

fun <P: KProperty1<*, *>> getReflectionHelper(clazz: P) = ReflectionHelper<P>()

class ReflectionHelper<P: KProperty1<*, *>> {
}

fun main(args : Array<String>) {
    println(reflectionHelper(Dog::age))  // Works
    val helper1 = getReflectionHelper(Dog::age)  // Also Works
    val helper2 = ReflectionHelper<Dog::age>()  // Error: Type inference failed
}
1

There are 1 best solutions below

0
On BEST ANSWER

Dog::age is a value (of type KProperty1<Dog, String>), not a type. In between < and > you need to put a type, or you need to omit them entirely and the type will be inferred (that's what happens in the first two lines).

So the equivalent to your funs would be

class ReflectionHelper<P: KProperty1<*, *>>(input: P) { ... }
val helper2 = ReflectionHelper(Dog::age)

If you don't need input: P as a parameter, you'll have to specify P explicitly both for fun and for class.