Scala maps -> operator

后端 未结 4 1119
离开以前
离开以前 2020-12-23 16:54

What does the symbol -> mean in the context of a Map in Scala?

Scala’s Predef class offers an implicit conversion that lets

4条回答
  •  失恋的感觉
    2020-12-23 17:18

    Here's the implicit conversion:

    implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x)
    

    This will convert any type into an instance of "ArrowAssoc"

    class ArrowAssoc[A](x: A) {
        def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y)
    }
    

    So when Scala sees

    "a"->1
    

    It says "There is no method named '->' on String. Are there any implicit conversions in scope that can give me a type that has a method named '->'?" Predef.scala is automatically in scope, and offers a conversion to ArrowAssoc, which obviously has the '->' method. Scala then essentially converts the above to

    any2ArrowAssoc("a").->(1)
    

    This method returns a Tuple2("a", 1) (often called a Pair). Map has a constructor that thats an array (varargs) of Tuple2s, so we're off to races! No magic in the compiler (besides implicit conversion, which is used extensively and for many different purposes), and no magic in Maps constructor.

提交回复
热议问题