Convert list to map and get item in one line

Try:

(List(('c', 1)).toMap)('c')

Error:

found   : Char('c')
required: <:<[(Char, Int),(?, ?)]

However, this works great:

val m = List(('c', 1)).toMap
m('c') // gives 1 as expected

Why does it matter whether to store it in a variable first or not? Could this be a mistake?

+4
source share
1 answer

The problem is that the full signature toMapis this:

def toMap[T, U](implicit ev: <:<[A, (T, U)]): Map[T, U]

Collection API designers did not want to compile List(1).toMap, so they require that you provide hidden evidence that the contents of the list are tuples.

- toMap , . - , toMap , , .

( , ) - apply. whatever(foo) whatever.apply(foo) ( whatever ), , :

scala> List(('c', 1)).toMap.apply('c')
res0: Int = 1

, toMap c .

+6

Source: https://habr.com/ru/post/1544235/


All Articles