Thomas Cook
Thomas Cook

Reputation: 4853

Retrieve return type from function

I was investigating how the compiler infers the return type of functions depending on the return statements. Then I came across something that perplexed me.

I have this Kotlin function:

fun ambigousTypeEval(sport: String) = when (sport) {
  "cricket" -> -1
  else -> "I like $sport"
}

It can return an Int OR a String, so it's compile time type is Any (i.e. if you call this function and assign it's return value to a variable, that variable will be of type Any).

However, when I load that code in the kotlinc REPL, and check it's type, I am getting a different type for different inputs...

>>> examples.ambigousTypeEval("cricket")::class
examples.ambigousTypeEval("cricket")class kotlin.Int

>>> examples.ambigousTypeEval("football")::class
examples.ambigousTypeEval("football")class kotlin.String

What's going on here?

EDIT: To be clear, I want to know how to find out the compile time type of the function. I.e. I was expecting to see something like: (String) -> Any

Upvotes: 0

Views: 733

Answers (1)

Salem
Salem

Reputation: 14887

Addressing the edit:

You must get a reference to the function first:

val func = examples::ambiguousTypeEval

This is a KFunction instance.

Now simply retrieve its returnType:

val returnType: KType = examples::ambiguousTypeEval.returnType

In this case, the return type will be a KType corresponding to Any.

You can retrieve the parameter types via parameters.

Upvotes: 3

Related Questions