Question

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
)
Était-ce utile?

La solution

Because you're requiring two implicits. The following:

something -> to somethingElse

syntax implicitly converts to a a Pair. Int to long is another compile time implicit conversion

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

Should work. The work sheet gives:

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

As a simple general rule Scala only allows one implicit conversion at a time. If it didn't complete madness would ensue and all compile time type safety would be lost.

If you find you're having to write this syntax a lot you can just create a simple factory method to convert from Ints to Longs. And if its performance critical then you can write a macro to convert.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top