Matthew Layton
Matthew Layton

Reputation: 42390

Kotlin - print function expressions

In C# I can represent a function expression like so

Expression<Func<int, int, int>> add = (a, b) => a + b;

The string representation of the function expression looks like this

(a, b) => (a + b)

In Kotlin I can represent a function expression like so

val add = { a: Int, b: Int -> a + b }

The string representation of the function expression looks like this

(kotlin.Int, kotlin.Int) -> kotlin.Int

Is there a way that Kotlin can represent the function expression more aligned to C#, showing the input parameters and the function body?

Upvotes: 1

Views: 378

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170919

val add = { a: Int, b: Int -> a + b }

is equivalent to

Func<int, int, int> add = (a, b) => a + b;

not to Expression<...>. And if you print that, you'll see something like System.Func<int, int, int>, like in Kotlin.

I don't think Kotlin has a type like Expression in the standard library, or that you can implement it without language support. Its reflection API is richer than Java's (see KFunction) but doesn't let you access the body. You could do it with byte code manipulation libraries, but it would be a lot of work.

Upvotes: 2

Related Questions