How do I fix this code? ```private val SUB_REGEXES...
# announcements
e
How do I fix this code?
Copy code
private 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
:
Copy code
private val SUB_REGEXES: Map<String, Pair<Regex, String>> =
  SUBSTITUTIONS.keys.associateWith { 
    Pair(Regex("\\b$it\\b", RegexOption.IGNORE_CASE), SUBSTITUTIONS[it]) 
}
I figured out that I needed to replace
SUBSTITUTIONS[it]
with
SUBSTITUTIONS.getValue(it)
.
This is essentially the same thing as
SUBSTITUTIONS[it]!!
but satisfies the compiler and linter. I still welcome a better solution.
m
Perhaps
mapValues()
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.
👆 1
🤔 1
Copy code
private 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)}
💯 1
e
Yes, that does it, @Mark Murphy. Thank you!
👍 1