Rachel Carandang
06/26/2022, 3:19 PMfun degreesToDirection(degrees: Float?): Direction {
var smallestDistance: Float = Float.POSITIVE_INFINITY
lateinit var direction: Direction
degreesMapping.entries.forEach {
if (abs(it.value - (degrees ?: 0f)) < smallestDistance) {
direction = it.key
smallestDistance = (degrees ?: 0f) - it.value
}
}
return direction
}
Joffrey
06/26/2022, 3:30 PMlateinit var
per se. But doing this sort of loop to initialize a variable in Kotlin is usually a smell. For instance, is it expected to iterate over all the mappings here? Usually the first match should stop the loopJavier
06/26/2022, 3:39 PMVampire
06/26/2022, 3:40 PMfun degreesToDirection(degrees: Float?) =
degreesMapping.minByOrNull { (_, mappedDegrees) ->
abs(mappedDegrees - (degrees ?: 0f))
}!!.key
For instance, is it expected to iterate over all the mappings here? Usually the first match should stop the loopFirst match, when searching for a minimum? 😉
Joffrey
06/26/2022, 3:48 PMStarr
06/26/2022, 3:49 PMVampire
06/26/2022, 3:50 PMJoffrey
06/26/2022, 3:52 PMminByOrNull
+ !!
Vampire
06/26/2022, 3:57 PMminBy
which is deprecated and should be replaced by minByOrNull
.Javier
06/26/2022, 3:59 PMVampire
06/26/2022, 4:01 PMfun degreesToDirection(degrees: Float?) =
degreesMapping.minWith(compareBy { (_, mappedDegrees) ->
abs(mappedDegrees - (degrees ?: 0f))
}).key
minBy
minBy
only not deprecated for common, js, and native, but deprecated for jvmJoffrey
06/26/2022, 7:00 PMVampire
06/26/2022, 8:23 PMRachel Carandang
06/26/2022, 9:12 PM