Which one is more idiomatic / preferable in Scala: Map (<material>: _ *) or <material> .toMap?

They seem virtually equivalent:

 scala> ("asd" zip "zxc").toMap res62: scala.collection.immutable.Map[Char,Char] = Map(a -> z, s -> x, d -> c) scala> Map(("asd" zip "zxc"): _*) res63: scala.collection.immutable.Map[Char,Char] = Map(a -> z, s -> x, d -> c) 

However, what are the differences in real life? Which one is more idiomatic? Will there be any other runtime performance?

I am sure that the same / similar question can be asked about other, similar pairs of constructs, so feel free to give a more general / abstract answer :)

+4
source share
2 answers

There is a real difference between the two due to where these methods are defined:

  • The apply constructor is defined in the companion of the target collection:

     object Coll { def apply[T](els: T*): Coll[T] = ??? } 

    This means that it has absolutely no input information other than Seq elements, so it just goes through this sequence and builds Coll .

  • on the other hand, toSeq , toArray , ... are defined in the original collection, that is, they have all the additional information about its internal components.

You can usually rely on toXXX methods to short-circuit when necessary, or to return some specialized collection that makes sense.

As a stupid example, consider:

 List(1,2,3).toSeq // toSeq returns `this`, there is no overhead // vs. Seq(List(1,2,3): _*) // this will copy that list into a new one... 

It gets worse if you replace this list with Stream.continually(1) ...

+3
source

I would prefer the first option, as it is more understandable and readable. There is no actual difference between the two characteristics or other characteristics. In the first case, you make the seq index, and then convert it to a card in the second, you use this seq extractor sintax :_* And this is the best part of Scala. Like Professor Odersky, many of many, he was part of Scala's design to provide design solutions for various tasks. Therefore, in this case, you can choose any. But, as I told you, the first one is more understandable and understandable, leave programming the kernel symbol to Scalaz =)

0
source

Source: https://habr.com/ru/post/1501199/


All Articles