2
votes

Consider the following code, where we take chunks of a list, join them and print to stdout:

val l = listOf("1", "2", "3", "4", "5", "6", "7")
l.chunked(3, { a -> a.joinToString()}).forEach(::println)

The code works without a problem. I wanted to change the lambda call ({ a -> a.joinToString()}) to the method reference, like this:

l.chunked(3, l::joinToString).forEach(::println)

The code that uses method reference does not compile and the errors given are:

Error:(4, 7) Kotlin: Type inference failed: fun Iterable.chunked(size: Int, transform: (List) -> R): List cannot be applied to receiver: List arguments: (Int,KFunction6<@ParameterName CharSequence, @ParameterName CharSequence, @ParameterName CharSequence, @ParameterName Int, @ParameterName CharSequence, @ParameterName(name = "transform") ((String) -> CharSequence)?, String>)

Error:(4, 18) Kotlin: Type mismatch: inferred type is KFunction6<@ParameterName CharSequence, @ParameterName CharSequence, @ParameterName CharSequence, @ParameterName Int, @ParameterName CharSequence, @ParameterName(name = "transform") ((String) -> CharSequence)?, String> but (List) -> ??? was expected

Error:(4, 21) Kotlin: Type inference failed: fun Iterable.joinToString(separator: CharSequence = ..., prefix: CharSequence = ..., postfix: CharSequence = ..., limit: Int = ..., truncated: CharSequence = ..., transform: ((T) -> CharSequence)? = ...): String cannot be applied to receiver: List arguments: ()

Is there a way to compile the code with method references instead of lambda call? I am beginning to learn Kotlin, but suppose that the errors stem from the fact that joinToString uses a number of default arguments?

1
Seems relevant: youtrack.jetbrains.com/issue/KT-8834 It has a target version of 1.3Michael
@Michael Seams very relevant! Can you consider changing your comment into an answer?lukeg

1 Answers

5
votes

There's an open feature request in the Kotlin issue tracker with the title "Support function references with default values as other function types", which seems to be what's missing for your use-case to work.

The feature currently has a target version of 1.3.

Update The 1.3 Kotlin release does not contain this feature, the target version is updated to 1.4