9

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
Michiel Leegwater
  • 1,172
  • 4
  • 11
  • 27
Zymus
  • 1,673
  • 1
  • 18
  • 38
  • 7
    There is an issue about this [here](https://youtrack.jetbrains.com/issue/KT-8834). – gpunto Sep 23 '19 at 22:00
  • 2
    I got it to work using `-XXLanguage:+NewInference` compiler argument as mentioned in that issue. – Pawel Sep 23 '19 at 22:14
  • 2
    @gpunto want to make an answer so I can accept? Useful to know of the experimental tag, and the intention to be in a future version of Kotlin. – Zymus Sep 23 '19 at 23:03

1 Answers1

1

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.

Zymus
  • 1,673
  • 1
  • 18
  • 38