1

Why do I need to write 'L' after each key in a Map in order to have a Map[Long, ...]? Is there another, less verbose way?

private[this] val periodById: Map[Long, X] = Map(
    1L -> OneSecond,
    4L -> TenSecond,
    5L -> ThirtySecond,
    10L -> OneMinute,
    50L -> FiveMinutes,
    100L -> TenMinutes
)
4

1 回答 1

3

因为你需要两个隐式。以下:

某物 -> 到某物Else

语法隐式转换为 aa Pair。int to long 是另一种编译时隐式转换

private[this] val periodById: Map[Long, X] = Map(
  (1, OneSecond),
  (4, TenSecond)
)

应该管用。工作表给出:

val m: Map[Long, Int] = Map((4, 5), (3, 2))
//> m  : Map[Long,Int] = Map(4 -> 5, 3 -> 2)
//My note the Worksheet is using Tuple2's to String method to display the x -> y notation.
m.getClass.getName
//> res1: String = scala.collection.immutable.Map$Map2
m.head.getClass.getName
//> res1: String = scala.Tuple2

作为一个简单的一般规则,Scala 一次只允许一个隐式转换。如果它没有完全疯狂,那么所有的编译时类型安全都将丢失。

如果你发现你不得不写很多这种语法,你可以创建一个简单的工厂方法来从 Ints 转换为 Longs。如果它的性能很关键,那么你可以编写一个宏来转换。

于 2013-10-24T09:27:50.947 回答