is it possible to use println as a function reference in Kotlin

Viewed 808

In Java 8 and 9 it is possible to have method references for printing to the console, like e.g:

List.of(1, 2, 3).forEach(System.out::println);

In Kotlin I did not find a way to use a method reference to print to the console. I have tried to translate this to use a function reference:

listOf(1, 2, 3).forEach { println(it) }

to:

listOf(1, 2, 3).forEach { ::println }

But I am getting this error:

Overload resolution ambiguity. All these functions match.
@InlineOnly public inline fun println(): Unit defined in kotlin.io
@InlineOnly public inline fun println(message: Any?): Unit defined in kotlin.io
@InlineOnly public inline fun println(message: Boolean): Unit defined in kotlin.io
@InlineOnly public inline fun println(message: Byte): Unit defined in kotlin.io
@InlineOnly public inline fun println(message: Char): Unit defined in kotlin.io
@InlineOnly public inline fun println(message: CharArray): Unit defined in kotlin.io
@InlineOnly public inline fun println(message: Double): Unit defined in kotlin.io
@InlineOnly public inline fun println(message: Float): Unit defined in kotlin.io
@InlineOnly public inline fun println(message: Int): Unit defined in kotlin.io
@InlineOnly public inline fun println(message: Long): Unit defined in kotlin.io
@InlineOnly public inline fun println(message: Short): Unit defined in kotlin.io

How can I solve this resolution ambiguity? Is it possible to use a function reference in this case?

1 Answers

The problem is that you're passing a function which in turn returns the function println, so the compiler can't figure out which println to return. What you want to do is use println itself as an argument, for which you need to use ():

listOf(1, 2, 3).forEach(::println)
Related