Type of a function type?

Is there any way to get the type of a function type, e.g.

foo((() -> Unit)::class)

but that actually works?

1 Like

It doesn’t seem like the normal syntax for it works sadly. However, this workaround is valid for now:

inline fun <reified T: Any> clazz() = T::class 

fun main() {
    println(clazz<() -> Unit>())
}

() -> Unit is translated to Function0<Unit> internally so Function0::class should work. Same with Function1 for functions with 1 argument, etc.

1 Like

You can also use a new API for types:

typeOf<() -> Unit>() // () -> kotlin.Unit
typeOf<() -> Unit>().jvmErasure // class kotlin.Function0
typeOf<() -> Unit>().jvmErasure.java // interface kotlin.jvm.functions.Function0
4 Likes

Is that still experimental?

It seems so. It’s been introduced since Kotlin 1.3.60, but it’s still marked as experimental.

That said, experimental is most likely save to use in this case. There are a few outstanding issues with typeof. The most problematic in my oppinion is that currently typeof<MutableList<String>() == typeof<List<String>>() evaluates to true (https://youtrack.jetbrains.com/issue/KT-35877).
For a “full” list you can check:

1 Like

Yes, I also noticed that when was experimenting with mutable collection interfaces.

Thanks everyone! Turns out we were following a bit of a misguided path tho so we didn’t actually need this? sorry >.<

1 Like