Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get a KFunction from a variable of function type in Kotlin?

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)) 
like image 765
Duncan McGregor Avatar asked May 02 '16 15:05

Duncan McGregor


People also ask

How does Kotlin define function type?

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) .

How do you pass list as parameters in Kotlin?

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.

What is KFunction in Kotlin?

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) { // ... }

What is the default return type of any functions defined in Kotlin?

I know unit is the default return type in kotlin.


1 Answers

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
}
like image 131
Kirill Rakhman Avatar answered Sep 30 '22 03:09

Kirill Rakhman