Sam Garfinkel
02/06/2020, 4:50 PMZach Klippenstein (he/him) [MOD]
02/06/2020, 4:54 PMSam Garfinkel
02/06/2020, 4:59 PMinline fun <reified T> foo() = funThatTakesKClass(T::class)
Works for functional types?diesieben07
02/06/2020, 5:02 PM() -> String
and () -> Unit
are the same class at runtime.Sam Garfinkel
02/06/2020, 5:03 PMSam Garfinkel
02/06/2020, 5:03 PMdiesieben07
02/06/2020, 5:03 PMZach Klippenstein (he/him) [MOD]
02/06/2020, 5:03 PMtypeOf()
diesieben07
02/06/2020, 5:04 PMkotlin.jvm.functions
directly, such as Function0::class
diesieben07
02/06/2020, 5:04 PMSam Garfinkel
02/06/2020, 5:05 PMdiesieben07
02/06/2020, 5:06 PMFunction1::class
works on JS also. But you might not be able to detect that something is of that type at runtime (as opposed to the JVM). Let me try some more.Sam Garfinkel
02/06/2020, 5:06 PMSam Garfinkel
02/06/2020, 5:07 PMdiesieben07
02/06/2020, 5:07 PMdiesieben07
02/06/2020, 5:07 PMdiesieben07
02/06/2020, 5:08 PMval lambda = { foo: String -> foo.toUpperCase() }
println(lambda is Function1)
println(lambda is Function0<*>)
Prints true
, false
on JVM, true
, true
on JS.Sam Garfinkel
02/06/2020, 5:08 PMSam Garfinkel
02/06/2020, 5:08 PMdiesieben07
02/06/2020, 5:08 PMdiesieben07
02/06/2020, 5:09 PMsingle<Foo> { ... }
that Foo
is reifieddiesieben07
02/06/2020, 5:09 PMget<Foo>()
Sam Garfinkel
02/06/2020, 5:09 PMdiesieben07
02/06/2020, 5:09 PMFunction0
, etc. things are.diesieben07
02/06/2020, 5:09 PMdiesieben07
02/06/2020, 5:10 PMSam Garfinkel
02/06/2020, 5:12 PMinterface Foo: Function1<String, String> {
override operator fun invoke(it: String): String
}
object bar: Foo { it ->
// does not work
}
diesieben07
02/06/2020, 5:12 PMdiesieben07
02/06/2020, 5:12 PMSam Garfinkel
02/06/2020, 5:12 PMdiesieben07
02/06/2020, 5:14 PMSam Garfinkel
02/06/2020, 5:18 PMinvoke
as whenever I want to create an instance of Foo
instead it would be nice to just treat Foo
as a function, but with a runtime name.Sam Garfinkel
02/06/2020, 5:18 PMdiesieben07
02/06/2020, 5:19 PMFunctionX
(you probably shouldn't do that anyways). operator fun invoke
works even without extending FunctionX
.diesieben07
02/06/2020, 5:20 PMinterface Foo {
operator fun invoke(arg: String): String
companion object {
inline operator fun invoke(crossinline body: (String) -> String): Foo {
return object : Foo {
override operator fun invoke(arg: String) = body(arg)
}
}
}
}
diesieben07
02/06/2020, 5:20 PMval myFoo = Foo { arg -> arg.toUpperCase }
diesieben07
02/06/2020, 5:23 PMval resultOfMyFoo = myFoo("hello world") // "HELLO WORLD"
Sam Garfinkel
02/06/2020, 5:24 PMSam Garfinkel
02/06/2020, 5:24 PM