I have a function which takes in a `KClass<T&gt...
# announcements
b
I have a function which takes in a
KClass<T>
and returns a function which takes a
String
and returns an instance `T`:
Copy code
fun <T : Any> getterFor(valueType: KClass<T>): (String) -> T
One issue with this is that, due to type erasure, it doesn't work for things like
List<Int>
. I know `typeOf`/`KType` can help with this, but is there a typesafe way I can refer to a
KType
argument's type in the return type position? I.e. before I have
T
which matches between the argument (
KClass<T>
) and the return type T...is there a way to do that with KType?
Copy code
fun getterFor(type: KType): (String) -> ???
I can do
Copy code
fun <T : Any> getterFor(type: KType): (String) -> T
and then cast to
T
, but wondering if there's a way to 'enforce' a relationship between the KType and the return value's type
z
Copy code
inline fun <reified T : Any> getterFor(): (String) -> T {
  @Suppress("UNCHECKED_CAST")
  return getterFor(typeOf<T>()) as (String) -> T
}

@PublishedApi internal fun getterFor(type: KType): (String) -> Any {
  …
}
b
🤦 Awesome. Thanks @Zach Klippenstein (he/him) [MOD].
I was trying to think of ways to use an intermediary function and that didn't occur to me.