What instance of CanBuildFrom did the Scala compiler recognize?

everyone. Please forgive me by asking a stupid question about Scala. Although I have been programming in Scala for about 2 years, it's still hard for me to understand the use of implicit . Take an example to discuss:

 Array(1,2,3,4).map(x => x) 

If you look at scaladoc, you cannot find the map method in the Array class. The reason map can be used on Array(1,2,3,4) is because there is an implicit function implicit def intArrayOps (xs: Array[Int]): ArrayOps[Int] defined in scala.Predef .

However, there are two parameter lists where the second is written as implicit bf: CanBuildFrom[Array[T], B, That]) . Now I wonder where the compiler finds the correct argument for the CanBuildFrom type when applying map to Array(1,2,3,4) .

+7
source share
2 answers

Implicit permission includes searching for a companion object for the type of the implicit parameter , and also companion objects for enter the parameters of the implicit parameter . In the example above, the card signature is as follows

 def map[B, That](f: (Int) => B)(implicit bf: CanBuildFrom[Array[Int], B, That]): That 

Since we have no type requirements for what we can ignore it at the moment. After we look in the local and container regions and find no matching implications, the next place to look for the implicit will be the companion object for CanBuildFrom. However, it does not have a companion object. Therefore, we continue and look into the array for implicit. Find one in the form

 implicit def canBuildFrom[T](implicit m: ClassManifest[T]): CanBuildFrom[Array[_], T, Array[T]] 

Since we do not have type requirements or implicit matching, "This" is forced to be of type Array [Int] and completes our typing.

+9
source

This question was partially answered by another question about StackOverflow. Let me try to summarize them:

The first part you need to know is where the Scala compiler searches for implicits . You can find more information about CanBuildFrom here .

If you understand what is mentioned in the implicit answers, you should take a look at the design of Scala Collections. Their inheritance hierarchy is explained here and for the list here . They all grow with the Builders. This is explained in detail in the breakOut question.

To combine your knowledge, you need to know how to pimp collections. Also, this is explained in StackOverflow in this question .

Please note that the best answers to StackOverflow are summarized in the Scala-Tag-Wiki .

+7
source

All Articles