I'm trying to get the name that a function was defined with
fun aFunction() = Unit
fun functionName(function: () -> Unit) : String {
val functionAsKFunction: KFunction<Unit> = someMiracle(function)
return functionAsKFunction.name
}
assertEquals("aFunction", functionName(::aFunction))
These names can be used for documenting the meaning of the parameters. To specify that a function type is nullable, use parentheses as follows: ((Int, Int) -> Int)? . Function types can also be combined using parentheses: (Int) -> ((Int) -> Unit) .
Create a new List using the Kotlin standard library function listOf() , and pass in the elements of the list as arguments separated by commas. listOf(1, 2, 3, 4, 5, 6) returns a read-only list of integers from 1 through 6.
KFunction is Kotlin's way to to wrap around reflected functions. As to making Any::toString work - there is a way but you may not like it: fun <T> doSomething(value: T, action: (t: T) -> String = Any::toString as (T) -> String) { // ... }
I know unit is the default return type in kotlin.
You can simply cast () -> Unit
to KFunction<*>
. Theoretically, this is an implementation detail, but I don't think it will ever break.
fun functionName(function: () -> Unit) : String {
val functionAsKFunction: KFunction<*> = function as KFunction<*>
return functionAsKFunction.name
}
Edit: Obviously, this won't work for lambdas (what name would you expect anyway?) To prevent crashes, you can use a safe cast like so:
fun functionName(function: () -> Unit) : String? {
val functionAsKFunction: KFunction<*> = function as? KFunction<*> ?: return null
return functionAsKFunction.name
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With