Search code examples
kotlincode-conversion

How to map a List to a Set while applying a method(Java to Kotlin code conversion)?


I have this code snippet in Java (this is an MCVE; actual code is more complex but has exact same issue):

enum StatusEnum { A, B, C; }

[...]

final static Set<String> names = Arrays.asList(StatusEnum.values())
        .stream().map(StatusEnum::name).collect(Collectors.toSet());

IntelliJ gave me the following automated conversion to Kotlin:

    internal val names = Arrays.asList(*StatusEnum.values())
        .stream().map<String>(Function<StatusEnum, String> { it.name })
        .collect<Set<String>, Any>(Collectors.toSet())

This unfortunately has compile errors:

  • Interface Function does not have constructors
  • Type inference failed. Expected type mismatch: inferred type is Collector!>! but Collector!>! was expected
  • Unresolved reference: it

This is my very first attempt at converting some code to Kotlin. I have reviewed the Functions and Lambdas section of the documentation. Still not clear what's going on here or how to fix it.


Solution

  • Use Kotlin methods instead of Java streams:

    val names = StatusEnum.values()
        .map { it.name }
        .toSet()