Mapができるまで
scala
パッケージ配下にいるMapたち
package | ||
---|---|---|
共通 | scala.collection | |
不変 | scala.collection.immutable | |
可変 | scala.collection.mutable |
scala> :paste // Entering paste mode (ctrl-D to finish) val im = Map("a" -> "A") // Exiting paste mode, now interpreting. im: scala.collection.immutable.Map[String,String] = Map(a -> A)
Mapをよぶときimport
はいらない、
なぜかはscala.Predef
が暗黙的にimport
されているから
で、実際にどんなのかっていうと
object Predef extends LowPriorityImplicits with DeprecatedPredef { ... /** @group aliases */ val Map = immutable.Map
というわけで何も明示しなかったらcollection.immutable.Map
がよばれる
あまりないと思うが、mutable
使いたい場合は明示的にimport
scala> :paste // Entering paste mode (ctrl-D to finish) import scala.collection.mutable val im = Map("a" -> "A") val m = mutable.Map("a" -> "A") // Exiting paste mode, now interpreting. import scala.collection.mutable im: scala.collection.immutable.Map[String,String] = Map(a -> A) m: scala.collection.mutable.Map[String,String] = Map(a -> A)
apply
2.12 -> 2.13でCanBuildFormがなくなった影響か、中身結構かわってたよね、おちついたらまたやる
ということでコードジャンプ
abstract class GenMapFactory[CC[A, B] <: GenMap[A, B] with GenMapLike[A, B, CC[A, B]]] { /** A collection of type $Coll that contains given key/value bindings. * @param elems the key/value pairs that make up the $coll * @tparam A the type of the keys * @tparam B the type of the associated values * @return a new $coll consisting key/value pairs given by `elems`. */ def apply[A, B](elems: (A, B)*): CC[A, B] = (newBuilder[A, B] ++= elems).result()
とりあえずここにとんでくる
シグネチャはみたまんまなんで、実装へ
def newBuilder[A, B]: Builder[(A, B), CC[A, B]] = new MapBuilder[A, B, CC[A, B]](empty[A, B])
MapBuilderへ
class MapBuilder[A, B, Coll <: scala.collection.GenMap[A, B] with scala.collection.GenMapLike[A, B, Coll]](empty: Coll) extends ReusableBuilder[(A, B), Coll] { protected var elems: Coll = empty ... def result: Coll = elems }
とりあえずもぐるのはここまでにしておいて、
つまりapply
の中身は、
1, GenMapFactory#apply
がKey: A
, Value: B
をうけとる
2, GenMapFactory#newBuilder
で空のBuilder
を生成する
3, 作ったBuilder
に引数で渡された(Key, Value)*
を追加(++=
)
4.