Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference of a Java static method of a type parametrized class in Kotlin

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
}
like image 990
czerny Avatar asked Jan 21 '26 20:01

czerny


1 Answers

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))
like image 70
Lino Avatar answered Jan 23 '26 11:01

Lino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!