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?