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
}
Dog::ageis a value (of typeKProperty1<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 beIf you don't need
input: Pas a parameter, you'll have to specifyPexplicitly both forfunand forclass.