Transforming Operators | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/7419-beginning-rxkotlin/lessons/24

micro optimization

fun String.romanNumeralIntValue(): Int = this.map { letter -> lookup[letter] }
        .fold(0) { acc: Int, y: Int? -> acc.plus(y!!) }

define Lookup map outside function so its not re declared.

and you could define lookup with a when() statement in a function and you wont have to use the “y!!” variable example.

val lookup: (Char) -> Int = { inChar ->
    when (inChar.toUpperCase()) {
        'I' -> 1
        'V' -> 5
        'X' -> 10
        'L' -> 50
        'D' -> 500
        'M' -> 1000
        'C' -> 100
        else -> 0
    }
}

@eoin_a Thank you for sharing your solution - much appreciated!

@macsimus Can you please help with this when you get a chance? Thank you - much appreciated! :]

actually i think the when was overkill tbh when thinking about it later. this is slighly better

 this.map { letter -> lookup[letter]  ?: 0 }
        .fold(0) { acc: Int, y: Int? -> acc.plus(y) }

if we use the original map.