Any other solution to this issue with type checking?

Any other solution to this issue with type checking?

Hey! I would like to know if there’s a non-“workaround” solution to a type checking issue I’m facing:

Imagine the following example function:

kt /** Calls [fn] with `num + 1`. */ fun <T> withPlus1(num: Int, fn: (num: Int) -> T): T = fn(num + 1)

What I would like to do is to provide a default

fn

argument to

withPlus1

.

Something like:

kt /** Calls [fn] with `num + 1`. [fn] defaults to stringifying its input. */ fun <T> withPlus1( num: Int, fn: (num: Int) -> T = { num: Int -> num.toString() } ): T = fn(num + 1)

The above doesn’t compile because

num.toString()

is of type

String

rather than

T

.

Casting

num.toString()

to

T

makes it so that I can’t call

withPlus1(5)

because there isn’t enough type information to infer that

T

is

String

(i.e. I would have to call

withPlus1<String>(5)

), which is a no-go.

The obvious “workaround” solution here is to create a second function that calls the first function with the my default

fn

, i.e.:

kt fun withPlus1(num: Int): String = withPlus1(num) { num: Int -> num.toString() }

However, is there any way to make this work without relying on a second function? I.e., by providing a default argument to the first version of the function? I played around with the

@BuilderInference

experimental directive but couldn’t get it to work. Am I missing something?

submitted by /u/YarnSphere
[link] [comments]