Skip to content

Instantly share code, notes, and snippets.

@jlacar
Created April 7, 2020 04:27
Show Gist options
  • Save jlacar/e272fffe9ed1c70889cc5d6aebdae454 to your computer and use it in GitHub Desktop.
Save jlacar/e272fffe9ed1c70889cc5d6aebdae454 to your computer and use it in GitHub Desktop.
Kotlin - Map.associateBy and Elvis operator
// Example of Map.associateBy() in Kotlin
// Map vowels to their positions in the alphabet
val vowels = "aeiou".toCharArray() // ['a', 'e', 'i', 'o', 'u']
// Map<Char, Int> = {a=1, e=5, i=9, o=15, u=21}
val positions = vowels.associateBy({ it }, { it.toInt() - 'a'.toInt() + 1 })
val letter = readLine()!!
println(positions[letter.first().toLowerCase()] ?: 0) // default == 0 if not a vowel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment