Scala: Option, Some and the ArrowAssoc operator - scala

I am trying to analyze the following piece of Scala code:
import java.nio.file._
import scala.Some
abstract class MyCustomDirectoryIterator[T](path:Path,someNumber:Int, anotherNum:Int) extends Iterator[T] {
def getCustomIterator(myPath:Path):Option[(DirectoryStream[Path],
Iterator[Path])] = try {
//we get the directory stream
val str = Files.newDirectoryStream(myPath)
//then we get the iterator out of the stream
val iter = str.iterator()
Some((str -> iter))
} catch {
case de:DirectoryIteratorException =>
printstacktrace(de.getMessage)
None
}
How do I interpert this piece of code: Some((str -> iter))
Yes, it is returning a value of type:
Option[(DirectoryStream[Path], Iterator[Path])]
The -> operator is, to the best of my understanding, ArrowAssoc from the scala.Predef package.
implicit final class ArrowAssoc[A] extends AnyVal
But I still do not understand what the -> thing is doing to give me a return value of type:
Option[(DirectoryStream[Path], Iterator[Path])]
Can the Scala experts out here throw more light on this? Is there any way to write the "Some(..)" thing in a more readable way? I do understand the role played by Some, though.

The -> operator just creates a tuple:
scala> 1 -> "one"
res0: (Int, String) = (1,one)
which is equivalent to
scala> (1, "one")
res1: (Int, String) = (1,one)
I was just going to add the source code, but Reactormonk has got there first ;-)
The -> method is made available on any object via the implicit ArrowAssoc class. Calling it on an object of type A, passing a parameter of type B, creates a Tuple2[A, B].

The usual case for the -> operator is
Map(1 -> "foo", 2 -> "bar")
which is the same as
Map((1, "foo"), (2, "bar"))
Which works because the signature for Map.apply is
def apply[A, B](elems: Tuple2[A, B]*): Map[A, B]
which means it takes tuples as arguments and constructs a Map from
it.
So
(1 -> "foo")
is equivalent to
(1, "foo")
From the compiler sources:
implicit final class ArrowAssoc[A](private val self: A) extends AnyVal {
#inline def -> [B](y: B): Tuple2[A, B] = Tuple2(self, y)
def →[B](y: B): Tuple2[A, B] = ->(y)
}
which tells you directly it's creating a tuple. And that 1 → "foo" works as well.

Related

Non-unary type constructor bounded by unary type constructor

The title is attempting to describe the following subtyping
implicitly[Map[Int, String] <:< Iterable[(Int, String)]]
Type parameter A is inferred to (Int, String) here
def foo[A](cc: Iterable[A]): A = cc.head
lazy val e: (Int, String) = foo(Map.empty[Int, String])
however attempting to achieve similar effect using type parameter bounds the best I can do is explicitly specifying arity of the type constructor like so
def foo[F[x,y] <: Iterable[(x,y)], A, B](cc: F[A, B]): (A, B) = cc.head
lazy val e: (Int, String) = foo(Map.empty[Int, String])
because the following errors
def foo[F[x] <: Iterable[x], A](cc: F[A]) = cc.head
lazy val e: (Int, String) = foo(Map.empty[Int, String])
// type mismatch;
// [error] found : A
// [error] required: (Int, String)
// [error] lazy val e: (Int, String) = foo(Map.empty[Int, String])
// [error] ^
Hence using Iterable as upper bound it seems we need one signature to handle unary type constructors Seq and Set, and a separate signature to handle 2-arity type constructor Map
def foo[F[x] <: Iterable[x], A](cc: F[A]): A // When F is Seq or Set
def foo[F[x,y] <: Iterable[(x,y)], A, B](cc: F[A, B]): (A, B) // When F is Map
Is there a way to have a single signature using type bounds that works for all three? Putting it differently, how could we write, say, an extension method that works across all collections?
I think the issue here is that F is set to Map, and kindness is wrong. You would have to have say: I have some type X, that extends F[A], so that when I upcast it, I can use it as F[A] - which in turn we want to be a subtype of Iterable[A]. If we ask about it this way, it sounds hard.
Which is why I personally would just stay at:
# def foo[A](x: Iterable[A]): A = x.head
defined function foo
# foo(List(1 -> "test"))
res24: (Int, String) = (1, "test")
# foo(Map(1 -> "test"))
res25: (Int, String) = (1, "test")
"Give me any x that is an instance of Iterable[A] for A".
If I had to do some derivation... I would probably also go this way. I think this limitation is the reason CanBuildFrom works the way it works - providing matching for part of the type is hard, especially in cases like Map, so let's provide a whole type at once as a parameter, to limit the number of inference needed.

scala implicit convertion and arrow

I'm struggling with my DSL building attempt
My method should take multiple pairs of (A, B), ideally I'm looking for this kind of code:
myMethod(
a1 -> b1,
a2 -> b2,
a3 -> b3)
my A and B classes happened to often be constructed with a single string parameter, so i added implicit converters looking like this:
implict def stringToA(s: String): A = new A(s)
implict def stringToB(s: String): B = new B(s)
but arrow operator(for pair construction) doesn't pick up implicit converters:
object Test {
case class A(s: String)
case class B(s: String)
def myMethod(pairs: (A, B)*): Unit = Unit
implicit def stringToA(s: String): A = A(s)
implicit def stringToB(s: String): B = B(s)
myMethod(new Tuple2("a", "b")) // works just fine
myMethod("a" -> "b") // Error: Type mismatch, expected: (Test.A, Test.B), actual: (String, String)
}
any ideas?
The -> method is made available on all Scala types by an implicit conversion (any2ArrowAssoc in scala.Predef). For reasons of sanity, Scala doesn't allow multiple implicit conversions to "chain" on the same expression. You could:
Define an explicit -> method on your A class. Unfortunately since the default implicit conversion would conflict with this you might then have to build your code with -Yno-predef to avoid the conflict
Define a method on your A class with a visually similar name that doesn't conflict, e.g. ~> or »
Call myMethod(("a", "b")) if you like that syntax (this syntax is supported directly, not via an implicit conversion)
Make myMethod accept (String, String)* and do the conversion to A and B inside.
Edit: You could also define an implicit conversion from (String, String) to (A, B) as #BenReich suggests.
You can define an implicit conversion from (String, String) to (A, B):
implicit def toABTuple(in: (String, String)) = (A(in._1), B(in._2))
It's failing because its converting to a tuple before applying your implicits, so it's not a plain String -> A/B anymore.

"Too many arguments" error in Scala superclass constructor but not in REPL

I am writing a class which extends Scala's immutable map with some custom constructor logic. As a simple example, say I want a map of integers to strings that is initialized as 1 -> "one", 2 -> "two". In the REPL I can write the following.
scala> import collection.immutable.HashMap
import collection.immutable.HashMap
scala> HashMap[Int, String](1->"one", 2->"two")
res0: scala.collection.immutable.HashMap[Int,String] = Map(1 -> one, 2 -> two)
In my program I'd like to use the same constructor call, but I get a "too many arguments for constructor" error when I try to put it in the class definition line.
scala> class MyMap extends HashMap[Int, String](1->"1", 2->"2")
<console>:8: error: too many arguments for constructor HashMap: ()scala.collection.immutable.HashMap[Int,String]
class MyMap extends HashMap[Int, String](1->"1", 2->"2")
^
Given that the way to call superclass constructors is in the class definition, I figured that any expression that creates a HashMap in the REPL should also work in the definition, but there's some subtlety I'm missing here.
(I think extending the concrete class HashMap instead of a trait is the right thing to do here because I want to use the default map implementation. Extending HashMap is what I'd do in Java, but I'm not 100% certain that extending concrete collection classes is the most Scalaesque way to operate.)
Because I want MyMap to be immutable, I need to specify the initial values at constructor time. I can trying doing the initialization inside the apply function of the companion object like so:
class MyMap extends HashMap[Int, String]
object MyMap {
def apply() = new MyMap ++ List(1 -> "one", 2 -> "two")
}
But MyMap() returns an immutable map instead of a MyMap.
What is the correct way to initialize MyMap?
This link about implementing Map with concrete types is relevant.
You get an error here because when you write Map() you don't call the constructor of Map. Instead you call the apply method of it's companion object (or more precise the apply method of one of its superclasses. See om-nom-noms comment):
scala> Map(1 -> "one")
res0: scala.collection.immutable.Map[Int,String] = Map(1 -> one)
scala> Map.apply(1 -> "one")
res1: scala.collection.immutable.Map[Int,String] = Map(1 -> one)
If you want to have an own Map implementation you need to create your own implementation. The easiest thing I came up with is:
object MyMap {
def apply(ts: (Int, String)*): MyMap[Int, String] = new MyMap(ts.toMap)
def apply(): MyMap[Int, String] = apply(1 -> "one", 2 -> "two")
}
class MyMap[A, B] private(t: Map[Int, B]) extends Map[Int, B] {
private val internalMap = t
def +[B1 >: B](kv: (Int, B1)) = new MyMap(internalMap + kv)
def -(key: Int) = new MyMap(internalMap - key)
def get(key: Int) = internalMap.get(key)
def iterator = internalMap.iterator
}
scala> MyMap()
res1: MyMap[Int,String] = Map(1 -> one, 2 -> two)

Mixing in generic traits in parameterized classes without duplicating type parameters

Let's assume I want to create a trait that I can mix in into any Traversable[T]. In the end, I want to be able to say things like:
val m = Map("name" -> "foo") with MoreFilterOperations
and have methods on MoreFilterOperations that are expressed in anything Traversable has to offer, such as:
def filterFirstTwo(f: (T) => Boolean) = filter(f) take 2
However, the problem is clearly that T is not defined as a type parameter on MoreFilterOperations. Once I do that, it's doable of course, but then my code would read:
val m = Map("name" -> "foo") with MoreFilterOperations[(String,String)]
or if I define a variable of this type:
var m2: Map[String,String] with MoreFilterOperations[(String,String)] = ...
which is way to verbose for my taste. I would like to have the trait defined in such a way that I could write the latter as:
var m2: Map[String,String] with MoreFilterOperations
I tried self types, abstract type members, but it hasn't resulted in anything useful. Any clues?
Map("name" -> "foo") is a function invocation and not a constructor, this means that you can't write:
Map("name" -> "foo") with MoreFilterOperations
any more that you can write
val m = Map("name" -> "foo")
val m2 = m with MoreFilterOperations
To get a mixin, you have to use a concrete type, a naive first attempt would be something like this:
def EnhMap[K,V](entries: (K,V)*) =
new collection.immutable.HashMap[K,V] with MoreFilterOptions[(K,V)] ++ entries
Using a factory method here to avoid having to duplicate the type params. However, this won't work, because the ++ method is just going to return a plain old HashMap, without the mixin!
The solution (as Sam suggested) is to use an implicit conversion to add the pimped method. This will allow you to transform the Map with all the usual techniques and still be able to use your extra methods on the resulting map. I'd normally do this with a class instead of a trait, as having constructor params available leads to a cleaner syntax:
class MoreFilterOperations[T](t: Traversable[T]) {
def filterFirstTwo(f: (T) => Boolean) = t filter f take 2
}
object MoreFilterOperations {
implicit def traversableToFilterOps[T](t:Traversable[T]) =
new MoreFilterOperations(t)
}
This allows you to then write
val m = Map("name"->"foo", "name2"->"foo2", "name3"->"foo3")
val m2 = m filterFirstTwo (_._1.startsWith("n"))
But it still doesn't play nicely with the collections framework. You started with a Map and ended up with a Traversable. That isn't how things are supposed to work. The trick here is to also abstract over the collection type using higher-kinded types
import collection.TraversableLike
class MoreFilterOperations[Repr <% TraversableLike[T,Repr], T] (xs: Repr) {
def filterFirstTwo(f: (T) => Boolean) = xs filter f take 2
}
Simple enough. You have to supply Repr, the type representing the collection, and T, the type of elements. I use TraversableLike instead of Traversable as it embeds its representation; without this, filterFirstTwo would return a Traversable regardless of the starting type.
Now the implicit conversions. This is where things get a bit trickier in the type notation. First, I'm using a higher-kinded type to capture the representation of the collection: CC[X] <: Traversable[X], this parameterises the CC type, which must be a subclass of Traversable (note the use of X as a placeholder here, CC[_] <: Traversable[_] does not mean the same thing).
There's also an implicit CC[T] <:< TraversableLike[T,CC[T]], which the compiler uses to statically guarantee that our collection CC[T] is genuinely a subclass of TraversableLike and so a valid argument for the MoreFilterOperations constructor:
object MoreFilterOperations {
implicit def traversableToFilterOps[CC[X] <: Traversable[X], T]
(xs: CC[T])(implicit witness: CC[T] <:< TraversableLike[T,CC[T]]) =
new MoreFilterOperations[CC[T], T](xs)
}
So far, so good. But there's still one problem... It won't work with maps, because they take two type parameters. The solution is to add another implicit to the MoreFilterOperations object, using the same principles as before:
implicit def mapToFilterOps[CC[KX,VX] <: Map[KX,VX], K, V]
(xs: CC[K,V])(implicit witness: CC[K,V] <:< TraversableLike[(K,V),CC[K,V]]) =
new MoreFilterOperations[CC[K,V],(K,V)](xs)
The real beauty comes in when you also want to work with types that aren't actually collections, but can be viewed as though they were. Remember the Repr <% TraversableLike in the MoreFilterOperations constructor? That's a view bound, and permits types that can be implicitly converted to TraversableLike as well as direct subclasses. Strings are a classic example of this:
implicit def stringToFilterOps
(xs: String)(implicit witness: String <%< TraversableLike[Char,String])
: MoreFilterOperations[String, Char] =
new MoreFilterOperations[String, Char](xs)
If you now run it on the REPL:
val m = Map("name"->"foo", "name2"->"foo2", "name3"->"foo3")
// m: scala.collection.immutable.Map[java.lang.String,java.lang.String] =
// Map((name,foo), (name2,foo2), (name3,foo3))
val m2 = m filterFirstTwo (_._1.startsWith("n"))
// m2: scala.collection.immutable.Map[java.lang.String,java.lang.String] =
// Map((name,foo), (name2,foo2))
"qaxfwcyebovjnbointofm" filterFirstTwo (_ < 'g')
//res5: String = af
Map goes in, Map comes out. String goes in, String comes out. etc...
I haven't tried it with a Stream yet, or a Set, or a Vector, but you can be confident that if you did, it would return the same type of collection that you started with.
It's not quite what you asked for, but you can solve this problem with implicits:
trait MoreFilterOperations[T] {
def filterFirstTwo(f: (T) => Boolean) = traversable.filter(f) take 2
def traversable:Traversable[T]
}
object FilterImplicits {
implicit def traversableToFilterOps[T](t:Traversable[T]) = new MoreFilterOperations[T] { val traversable = t }
}
object test {
import FilterImplicits._
val m = Map("name" -> "foo", "name2" -> "foo2", "name3" -> "foo3")
val r = m.filterFirstTwo(_._1.startsWith("n"))
}
scala> test.r
res2: Traversable[(java.lang.String, java.lang.String)] = Map((name,foo), (name2,foo2))
Scala standard library uses implicits for this purpose. E.g. "123".toInt. I think its the best way in this case.
Otherwise you'll have to go through full implementation of your "map with additional operations" since immutable collections require creation of new instances of your new mixed class.
With mutable collections you could do something like this:
object FooBar {
trait MoreFilterOperations[T] {
this: Traversable[T] =>
def filterFirstTwo(f: (T) => Boolean) = filter(f) take 2
}
object moreFilterOperations {
def ~:[K, V](m: Map[K, V]) = new collection.mutable.HashMap[K, V] with MoreFilterOperations[(K, V)] {
this ++= m
}
}
def main(args: Array[String]) {
val m = Map("a" -> 1, "b" -> 2, "c" -> 3) ~: moreFilterOperations
println(m.filterFirstTwo(_ => true))
}
}
I'd rather use implicits.

Scala 2.8 breakOut

In Scala 2.8, there is an object in scala.collection.package.scala:
def breakOut[From, T, To](implicit b : CanBuildFrom[Nothing, T, To]) =
new CanBuildFrom[From, T, To] {
def apply(from: From) = b.apply() ; def apply() = b.apply()
}
I have been told that this results in:
> import scala.collection.breakOut
> val map : Map[Int,String] = List("London", "Paris").map(x => (x.length, x))(breakOut)
map: Map[Int,String] = Map(6 -> London, 5 -> Paris)
What is going on here? Why is breakOut being called as an argument to my List?
The answer is found on the definition of map:
def map[B, That](f : (A) => B)(implicit bf : CanBuildFrom[Repr, B, That]) : That
Note that it has two parameters. The first is your function and the second is an implicit. If you do not provide that implicit, Scala will choose the most specific one available.
About breakOut
So, what's the purpose of breakOut? Consider the example given for the question, You take a list of strings, transform each string into a tuple (Int, String), and then produce a Map out of it. The most obvious way to do that would produce an intermediary List[(Int, String)] collection, and then convert it.
Given that map uses a Builder to produce the resulting collection, wouldn't it be possible to skip the intermediary List and collect the results directly into a Map? Evidently, yes, it is. To do so, however, we need to pass a proper CanBuildFrom to map, and that is exactly what breakOut does.
Let's look, then, at the definition of breakOut:
def breakOut[From, T, To](implicit b : CanBuildFrom[Nothing, T, To]) =
new CanBuildFrom[From, T, To] {
def apply(from: From) = b.apply() ; def apply() = b.apply()
}
Note that breakOut is parameterized, and that it returns an instance of CanBuildFrom. As it happens, the types From, T and To have already been inferred, because we know that map is expecting CanBuildFrom[List[String], (Int, String), Map[Int, String]]. Therefore:
From = List[String]
T = (Int, String)
To = Map[Int, String]
To conclude let's examine the implicit received by breakOut itself. It is of type CanBuildFrom[Nothing,T,To]. We already know all these types, so we can determine that we need an implicit of type CanBuildFrom[Nothing,(Int,String),Map[Int,String]]. But is there such a definition?
Let's look at CanBuildFrom's definition:
trait CanBuildFrom[-From, -Elem, +To]
extends AnyRef
So CanBuildFrom is contra-variant on its first type parameter. Because Nothing is a bottom class (ie, it is a subclass of everything), that means any class can be used in place of Nothing.
Since such a builder exists, Scala can use it to produce the desired output.
About Builders
A lot of methods from Scala's collections library consists of taking the original collection, processing it somehow (in the case of map, transforming each element), and storing the results in a new collection.
To maximize code reuse, this storing of results is done through a builder (scala.collection.mutable.Builder), which basically supports two operations: appending elements, and returning the resulting collection. The type of this resulting collection will depend on the type of the builder. Thus, a List builder will return a List, a Map builder will return a Map, and so on. The implementation of the map method need not concern itself with the type of the result: the builder takes care of it.
On the other hand, that means that map needs to receive this builder somehow. The problem faced when designing Scala 2.8 Collections was how to choose the best builder possible. For example, if I were to write Map('a' -> 1).map(_.swap), I'd like to get a Map(1 -> 'a') back. On the other hand, a Map('a' -> 1).map(_._1) can't return a Map (it returns an Iterable).
The magic of producing the best possible Builder from the known types of the expression is performed through this CanBuildFrom implicit.
About CanBuildFrom
To better explain what's going on, I'll give an example where the collection being mapped is a Map instead of a List. I'll go back to List later. For now, consider these two expressions:
Map(1 -> "one", 2 -> "two") map Function.tupled(_ -> _.length)
Map(1 -> "one", 2 -> "two") map (_._2)
The first returns a Map and the second returns an Iterable. The magic of returning a fitting collection is the work of CanBuildFrom. Let's consider the definition of map again to understand it.
The method map is inherited from TraversableLike. It is parameterized on B and That, and makes use of the type parameters A and Repr, which parameterize the class. Let's see both definitions together:
The class TraversableLike is defined as:
trait TraversableLike[+A, +Repr]
extends HasNewBuilder[A, Repr] with AnyRef
def map[B, That](f : (A) => B)(implicit bf : CanBuildFrom[Repr, B, That]) : That
To understand where A and Repr come from, let's consider the definition of Map itself:
trait Map[A, +B]
extends Iterable[(A, B)] with Map[A, B] with MapLike[A, B, Map[A, B]]
Because TraversableLike is inherited by all traits which extend Map, A and Repr could be inherited from any of them. The last one gets the preference, though. So, following the definition of the immutable Map and all the traits that connect it to TraversableLike, we have:
trait Map[A, +B]
extends Iterable[(A, B)] with Map[A, B] with MapLike[A, B, Map[A, B]]
trait MapLike[A, +B, +This <: MapLike[A, B, This] with Map[A, B]]
extends MapLike[A, B, This]
trait MapLike[A, +B, +This <: MapLike[A, B, This] with Map[A, B]]
extends PartialFunction[A, B] with IterableLike[(A, B), This] with Subtractable[A, This]
trait IterableLike[+A, +Repr]
extends Equals with TraversableLike[A, Repr]
trait TraversableLike[+A, +Repr]
extends HasNewBuilder[A, Repr] with AnyRef
If you pass the type parameters of Map[Int, String] all the way down the chain, we find that the types passed to TraversableLike, and, thus, used by map, are:
A = (Int,String)
Repr = Map[Int, String]
Going back to the example, the first map is receiving a function of type ((Int, String)) => (Int, Int) and the second map is receiving a function of type ((Int, String)) => String. I use the double parenthesis to emphasize it is a tuple being received, as that's the type of A as we saw.
With that information, let's consider the other types.
map Function.tupled(_ -> _.length):
B = (Int, Int)
map (_._2):
B = String
We can see that the type returned by the first map is Map[Int,Int], and the second is Iterable[String]. Looking at map's definition, it is easy to see that these are the values of That. But where do they come from?
If we look inside the companion objects of the classes involved, we see some implicit declarations providing them. On object Map:
implicit def canBuildFrom [A, B] : CanBuildFrom[Map, (A, B), Map[A, B]]
And on object Iterable, whose class is extended by Map:
implicit def canBuildFrom [A] : CanBuildFrom[Iterable, A, Iterable[A]]
These definitions provide factories for parameterized CanBuildFrom.
Scala will choose the most specific implicit available. In the first case, it was the first CanBuildFrom. In the second case, as the first did not match, it chose the second CanBuildFrom.
Back to the Question
Let's see the code for the question, List's and map's definition (again) to see how the types are inferred:
val map : Map[Int,String] = List("London", "Paris").map(x => (x.length, x))(breakOut)
sealed abstract class List[+A]
extends LinearSeq[A] with Product with GenericTraversableTemplate[A, List] with LinearSeqLike[A, List[A]]
trait LinearSeqLike[+A, +Repr <: LinearSeqLike[A, Repr]]
extends SeqLike[A, Repr]
trait SeqLike[+A, +Repr]
extends IterableLike[A, Repr]
trait IterableLike[+A, +Repr]
extends Equals with TraversableLike[A, Repr]
trait TraversableLike[+A, +Repr]
extends HasNewBuilder[A, Repr] with AnyRef
def map[B, That](f : (A) => B)(implicit bf : CanBuildFrom[Repr, B, That]) : That
The type of List("London", "Paris") is List[String], so the types A and Repr defined on TraversableLike are:
A = String
Repr = List[String]
The type for (x => (x.length, x)) is (String) => (Int, String), so the type of B is:
B = (Int, String)
The last unknown type, That is the type of the result of map, and we already have that as well:
val map : Map[Int,String] =
So,
That = Map[Int, String]
That means breakOut must, necessarily, return a type or subtype of CanBuildFrom[List[String], (Int, String), Map[Int, String]].
I'd like to build upon Daniel's answer. It was very thorough, but as noted in the comments, it doesn't explain what breakout does.
Taken from Re: Support for explicit Builders (2009-10-23), here is what I believe breakout does:
It gives the compiler a suggestion as to which Builder to choose implicitly (essentially it allows the compiler to choose which factory it thinks fits the situation best.)
For example, see the following:
scala> import scala.collection.generic._
import scala.collection.generic._
scala> import scala.collection._
import scala.collection._
scala> import scala.collection.mutable._
import scala.collection.mutable._
scala>
scala> def breakOut[From, T, To](implicit b : CanBuildFrom[Nothing, T, To]) =
| new CanBuildFrom[From, T, To] {
| def apply(from: From) = b.apply() ; def apply() = b.apply()
| }
breakOut: [From, T, To]
| (implicit b: scala.collection.generic.CanBuildFrom[Nothing,T,To])
| java.lang.Object with
| scala.collection.generic.CanBuildFrom[From,T,To]
scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)
scala> val imp = l.map(_ + 1)(breakOut)
imp: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 3, 4)
scala> val arr: Array[Int] = l.map(_ + 1)(breakOut)
imp: Array[Int] = Array(2, 3, 4)
scala> val stream: Stream[Int] = l.map(_ + 1)(breakOut)
stream: Stream[Int] = Stream(2, ?)
scala> val seq: Seq[Int] = l.map(_ + 1)(breakOut)
seq: scala.collection.mutable.Seq[Int] = ArrayBuffer(2, 3, 4)
scala> val set: Set[Int] = l.map(_ + 1)(breakOut)
seq: scala.collection.mutable.Set[Int] = Set(2, 4, 3)
scala> val hashSet: HashSet[Int] = l.map(_ + 1)(breakOut)
seq: scala.collection.mutable.HashSet[Int] = Set(2, 4, 3)
You can see the return type is implicitly chosen by the compiler to best match the expected type. Depending on how you declare the receiving variable, you get different results.
The following would be an equivalent way to specify a builder. Note in this case, the compiler will infer the expected type based on the builder's type:
scala> def buildWith[From, T, To](b : Builder[T, To]) =
| new CanBuildFrom[From, T, To] {
| def apply(from: From) = b ; def apply() = b
| }
buildWith: [From, T, To]
| (b: scala.collection.mutable.Builder[T,To])
| java.lang.Object with
| scala.collection.generic.CanBuildFrom[From,T,To]
scala> val a = l.map(_ + 1)(buildWith(Array.newBuilder[Int]))
a: Array[Int] = Array(2, 3, 4)
Daniel Sobral's answer is great, and should be read together with Architecture of Scala Collections (Chapter 25 of Programming in Scala).
I just wanted to elaborate on why it is called breakOut:
Why is it called breakOut?
Because we want to break out of one type and into another:
Break out of what type into what type? Lets look at the map function on Seq as an example:
Seq.map[B, That](f: (A) -> B)(implicit bf: CanBuildFrom[Seq[A], B, That]): That
If we wanted to build a Map directly from mapping over the elements of a sequence such as:
val x: Map[String, Int] = Seq("A", "BB", "CCC").map(s => (s, s.length))
The compiler would complain:
error: type mismatch;
found : Seq[(String, Int)]
required: Map[String,Int]
The reason being that Seq only knows how to build another Seq (i.e. there is an implicit CanBuildFrom[Seq[_], B, Seq[B]] builder factory available, but there is NO builder factory from Seq to Map).
In order to compile, we need to somehow breakOut of the type requirement, and be able to construct a builder that produces a Map for the map function to use.
As Daniel has explained, breakOut has the following signature:
def breakOut[From, T, To](implicit b: CanBuildFrom[Nothing, T, To]): CanBuildFrom[From, T, To] =
// can't just return b because the argument to apply could be cast to From in b
new CanBuildFrom[From, T, To] {
def apply(from: From) = b.apply()
def apply() = b.apply()
}
Nothing is a subclass of all classes, so any builder factory can be substituted in place of implicit b: CanBuildFrom[Nothing, T, To]. If we used the breakOut function to provide the implicit parameter:
val x: Map[String, Int] = Seq("A", "BB", "CCC").map(s => (s, s.length))(collection.breakOut)
It would compile, because breakOut is able to provide the required type of CanBuildFrom[Seq[(String, Int)], (String, Int), Map[String, Int]], while the compiler is able to find an implicit builder factory of type CanBuildFrom[Map[_, _], (A, B), Map[A, B]], in place of CanBuildFrom[Nothing, T, To], for breakOut to use to create the actual builder.
Note that CanBuildFrom[Map[_, _], (A, B), Map[A, B]] is defined in Map, and simply initiates a MapBuilder which uses an underlying Map.
Hope this clears things up.
A simple example to understand what breakOut does:
scala> import collection.breakOut
import collection.breakOut
scala> val set = Set(1, 2, 3, 4)
set: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 4)
scala> set.map(_ % 2)
res0: scala.collection.immutable.Set[Int] = Set(1, 0)
scala> val seq:Seq[Int] = set.map(_ % 2)(breakOut)
seq: Seq[Int] = Vector(1, 0, 1, 0) // map created a Seq[Int] instead of the default Set[Int]