Search code examples
kotlinlambdabuilder-pattern

How can I improve readability of this Kotlin code?


I want to improve this code in Kotlin, it seems too redundant

It should be possible with .forEach and Lambda's, but I don't know how Can anyone help please?


val Point1 : List<Double> = topleft
                .split(",")
                .map {
                    it
                            .trim()
                            .toDouble()
                }
        val Point2 : List<Double> = topright
                .split(",")
                .map {
                    it
                            .trim()
                            .toDouble()
                }
        val Point3 : List<Double> = bottomright
                .split(",")
                .map {
                    it
                            .trim()
                            .toDouble()
                }
        val Point4 : List<Double> = bottomleft
                .split(",")
                .map {
                    it
                            .trim()
                            .toDouble()
                }

In the end I want to have ONE List with all this values. topleft, topright ... are Strings like 42.1234,54.23423
(Geographical Coordinates)


Solution

  • You should create a function that you can repeat for each of your lists. Like this:

    fun String.splitToDoubles() = split(",").map { it.trim().toDouble() }
    
    val point1 = topleft.splitToDoubles()
    val point2 = topright.splitToDoubles()
    val point3 = bottomright.splitToDoubles()
    val point4 = bottomleft.splitToDoubles()
    

    Note that the convention in Kotlin is to have vals and vars starting with a lower case letter (point1, instead of Point1).