Ellen Spertus
02/02/2020, 12:32 AMprivate val SUB_REGEXES: Map<String, Pair<Regex, String>> =
SUBSTITUTIONS.keys.associate {
it to Pair(Regex("\\b$it\\b", RegexOption.IGNORE_CASE), SUBSTITUTIONS[it])
}
It doesn’t compile because SUBSTITUTIONS[it] is of type String? instead of the needed `String`; however, I know it is always a String because its key is in the map SUBSTITUTIONS.
Here’s a rewrite with associateWith :
private val SUB_REGEXES: Map<String, Pair<Regex, String>> =
SUBSTITUTIONS.keys.associateWith {
Pair(Regex("\\b$it\\b", RegexOption.IGNORE_CASE), SUBSTITUTIONS[it])
}Ellen Spertus
02/02/2020, 12:48 AMSUBSTITUTIONS[it] with SUBSTITUTIONS.getValue(it) .Ellen Spertus
02/02/2020, 12:49 AMSUBSTITUTIONS[it]!! but satisfies the compiler and linter. I still welcome a better solution.Mark Murphy
02/02/2020, 12:56 AMmapValues() is a better option: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-values.html You seem to want a Map whose keys are the same as the input Map but with different values, and that is what mapValues() should do for you.Mark Murphy
02/02/2020, 1:01 AMprivate val SUBSTITUTIONS = mapOf("foo" to "bar")
private val SUB_REGEXES: Map<String, Pair<Regex, String>> =
SUBSTITUTIONS.mapValues { (key, value) ->
Pair(Regex("\\b$key\\b", RegexOption.IGNORE_CASE), value)
}
fun main() {
println(SUB_REGEXES)
}
output is: {foo=(/\bfoo\b/gi, bar)}Ellen Spertus
02/02/2020, 1:04 AM