Scala - How to define map, where value depends on key?

dictionary, scala

Solution

Lets say you have your keys in a list like this, and you want to convert it map with squares as values.

scala> val keyList = ( 1 to 10 ).toList
keyList: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> val doSquare = ( x: Int ) => x * x
doSquare: Int => Int = <function1>

// Convert it to the list of tuples - ( key, doSquare( key ) )
scala> val tupleList = keyList.map( key => ( key, doSquare( key ) ) )
tuple: List[(Int, Int)] = List((1,1), (2,4), (3,9), (4,16), (5,25), (6,36), (7,49), (8,64), (9,81), (10,100))

val keyMap = tuple.toMap
keyMap: scala.collection.immutable.Map[Int,Int] = Map(5 -> 25, 10 -> 100, 1 -> 1, 6 -> 36, 9 -> 81, 2 -> 4, 7 -> 49, 3 -> 9, 8 -> 64, 4 -> 16)

Or to do it in one line

( 1 to 10 ).toList.map( x => ( x, x * x ) ).toMap

Or... if you have just few keys... then you can write the specific code

Map( 1 -> doSquare( 1 ), 2 -> doSquare( 2 ) )

Problem

Is there a way to define a Map, where Map value depends on its key, like ``` Map(key -> f(key), key2 -> f(key2), ...). ```

Original source