Search code examples
kotlingradlegradlewgradle-kotlin-dsl

Arraylist in koitlin from groovy


I am trying to migrate from gradle groovy based to kotlin and want to convert the below code for ArrayList in kotlin.

jmUserProperties = new ArrayList();
project.properties.each{ k, v -> jmUserProperties << "${k}=" + "${v}" }

Any reference on how to convert above logic to kotlin.


Solution

  • It really depends on the type of properties, but given your code above I think we can assume it's a Map. If that's the case then you can use the following code to map (i.e. transform) each key-value pair of your Map instance into a List of something else (in this case a list of Strings):

    val jmUserProperties = properties.map { (key, value) -> "$key=$value" }
    

    Note the resulting List is immutable (i.e. you can't add/remove values) and hence is not an instance of ArrayList. If you need a mutable list (i.e. if you want to be able to add/remove items) then you can use:

    val jmUserProperties = properties.map { (key, value) -> "$key=$value" }.toMutableList()
    

    Again, this won't necessarily return an ArrayList (in practice it does, but that's an implementation detail that can change at any time).

    If you want to be sure to get back an ArrayList you can use:

    val jmUserProperties = ArrayList(properties.map { (key, value) -> "$key=$value" })
    

    Complete example:

    // create a starting Map
    val properties = mapOf(
            "key1" to "value1",
            "key2" to "value2",
            "key3" to "value3"
    )
    
    // transform the map into an ArrayList<String>
    val jmUserProperties = ArrayList(properties.map { (key, value) -> "$key=$value" })
    
    // do something with the resulting ArrayList
    println(jmUserProperties)
    
    // confirm it's an ArrayList by printing its type to stdout
    println(jmUserProperties::class.java)
    

    That prints:

    [key1=value1, key2=value2, key3=value3]
    class java.util.ArrayList
    

    More info on what properties.map { (key, value) -> "$key=$value" } actually means:

    • map is a function that can be invoked (typically) on collections and allows transforming a Collection<A> into a List<B> and takes a mapping function that transforms objects of type A into objects of type B (much like collect in Groovy). The syntax of the lambda should look familiar if you know Groovy.
    • (key, value) is a destructuring declaration and basically in this case is used to extract a key and a value from an object of type Map.Entry (which is what Maps contain in Java). More info in the documentation I linked before