How to write method reference to a Java static method of a generic class in Kotlin?
Example below shows that ::
operator works only in case of non-generic classes (Colections
in this case). However using the same approach doesn't seem to work for List
interface that has a type parameter.
import java.util.Collections
import java.util.List
fun toSingletonList(item: Int, toList: (Int) -> MutableList<Int>): MutableList<Int> {
return toList(item)
}
fun main() {
println(toSingletonList(1, { Collections.singletonList(it) }))
println(toSingletonList(1, Collections::singletonList))
println(toSingletonList(1, { List.of(it) }))
println(toSingletonList(1, List::of)) // not compilable: One type argument expected for interface List<E : Any!>
println(toSingletonList(1, List<Int>::of)) // not compilable: Unresolved reference: of
}
You can import the of()
method directly:
import java.util.List.of
And then you're able to reference it directly:
println(toSingletonList(1, ::of))
If you happen to run into conflicts. E.g. by importing also Set.of
you may use import aliasing:
import java.util.List.of as jListOf
import java.util.Set.of as jSetOf
and then use that alias as a method reference
println(toSingletonList(1, ::jListOf))
println(toSingletonSet(1, ::jSetOf))