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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With