Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get a function reference to a function with default parameters in Kotlin, as the parameterless function?

Is it possible to get a function reference to a function which has default parameters, specified as the parameterless call?

InputStream.buffered() is an extension method which transforms an InputStream into a BufferedInputStream with a buffer size of 8192 bytes.

public inline fun InputStream.buffered(bufferSize: Int = DEFAULT_BUFFER_SIZE): BufferedInputStream =
    if (this is BufferedInputStream) this else BufferedInputStream(this, bufferSize)

I would like to effectively reference the extension method, with the default parameters, and pass that to another function.

fun mvce() {
    val working: (InputStream) -> InputStream = { it.buffered() }

    val doesNotCompile: (InputStream) -> BufferedInputStream = InputStream::buffered
    val alsoDoesNotCompile: (InputStream) -> InputStream = InputStream::buffered
}

doesNotCompile and alsoDoesNotCompile produce the following error

Type mismatch: inferred type is KFunction2 but (InputStream) -> BufferedInputStream was expected

Type mismatch: inferred type is KFunction2 but (InputStream) -> InputStream was expected

I understand the error is because InputStream.buffered() isn't actually (InputStream) -> BufferedInputStream, but instead a shortcut for (InputStream, Int) -> BufferedInputStream, passing the buffer size as a parameter to the BufferedInputStream constructor.

The motivation is primarily style reasons, I'd rather use references that already exist, than create one at the last moment

val ideal: (InputStream) -> BufferedInputStream = InputStream::buffered// reference extension method with default parameter
val working: (InputStream) -> BufferedInputStream = { it.buffered() }// create new (InputStream) -> BufferedInputStream, which calls extension method
like image 480
Zymus Avatar asked Sep 23 '19 21:09

Zymus


1 Answers

As gpunto and Pawel mentioned in the comments, using the -XXLanguage:+NewInference compiler argument allows function references with default values.

The issue is tracked here, and is targeted for Kotlin 1.4.0.

like image 80
Zymus Avatar answered Nov 18 '22 12:11

Zymus