Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looking for a more idiomatic way to do conditional logging during a list map

There’s gotta be a more Kotlin-esque and terse way to do this in Kotlin, but it’s not coming to me. Imagine you’re doing a mapNotNull operation. Items which cannot be mapped are converted to null to be filtered out. Items that cannot be mapped also result in a warning being printed. This code works, but it’s really verbose. Can you help me trim it down?

    val listOfStrings = listOf("1","2","3","not an int", "4","5")

    val convertedToInts = listOfStrings.mapNotNull {
        val converted = it.toIntOrNull()
        if(converted == null){
            println("warning, cannot convert '$it' to an int")
        }
        converted
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think your code is idiomatic and readable as it is. I prefer to write it with the explicit null-check.

But if you really want to make a shorter one-liner, you could do something like below. But it looks very hacky with the null.apply {} which is needed to return null instead of Unit from the right side of the elvis-operator:

val listOfStrings = listOf("1","2","3","not an int", "4","5")

val convertedToInts: List<Int> = listOfStrings.mapNotNull {
    it.toIntOrNull() 
        ?: null.apply { println("warning, cannot convert '$it' to an int") }
}

You could also use run which looks a bit more readable:

?: run { 
    println("warning, cannot convert '$it' to an int")
    null
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading