Scala: How to create a Map[K,V] from a Set[K] and a function from K to V?

前端 未结 7 1203
栀梦
栀梦 2020-12-15 07:37

What is the best way to create a Map[K,V] from a Set[K] and function from K to V?

For example, suppose I have

相关标签:
7条回答
  • 2020-12-15 08:20
    scala> import collection.breakOut
    import collection.breakOut
    
    scala> val set = Set(2,3,5)
    set: scala.collection.immutable.Set[Int] = Set(2, 3, 5)
    
    scala> def func(i: Int) = ""+i+i
    func: (i: Int)java.lang.String
    
    scala> val map: Map[Int,String] = set.map(i => i -> func(i))(breakOut)
    map: Map[Int,String] = Map(2 -> 22, 3 -> 33, 5 -> 55)
    
    scala>
    
    0 讨论(0)
提交回复
热议问题