Chapter 1

  1. Describe two ways to make it possible for some resource, R, to be used together with the scala.util.Using resource management utility. 

Let R extend java.lang.AutoCloseable. This will allow existing implicit conversion from AutoCloseable into Resource to be applied to R.

Provide an implicit implementation of Resource[R].

  1. How can Set and List be compared?

Equality is not defined between Set and List, hence we have to use the sameElements method in one of two ways, directly on List or on the iterator of Set, as shown in the following snippet:

val set = Set(1,2,3)
val list = List(1,2,3)

set == list // false

set.iterator.sameElements(list) // true

list.sameElements(set) // true

Another possibility is to utilize the corresponds operation in combination with the equality checking function. This works similar in either direction:

scala> set.corresponds(list)(_ == _)
res2: Boolean = true
scala> list.corresponds(set)(_ == _)
res3: Boolean = true
  1. Name the default concrete implementation for an immutable Seq.

scala.collection.immutable.List

  1. Name the default concrete implementation for an immutable indexed Seq.

scala.collection.immutable.Vector

  1. Name the default concrete implementation for a mutable Seq.

scala.collection.mutable.ArrayBuffer

  1. Name the default concrete implementation for a mutable IndexedSeq.

scala.collection.mutable.ArrayBuffer

  1. It is sometimes said that List.flatMap is more powerful than it is expected to be. Can you try to explain why? 

flatMap is defined on IterableOnce and hence takes a function returning IterableOnce as its argument. Because of this, it is possible to mix different types while flatMap pings. Consider the following example where List is able to flatMap the collection with Set[Int] and  as its elements:

scala> List(1,2,3,4,5,6).flatMap(i => if (i<3) Set.fill(i)(i) else Seq.fill(i)(i))
res28: List[Int] = List(1, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6)
  1. Describe a way to map over a collection multiple times using different functions but without producing intermediate collections.

Create a view, map over the view as required, and force conversion back to the original representation type:

scala> List(1,2,3,4,5).view.flatMap(List.fill(_)("a")).map(_.toUpperCase).toList
res33: List[String] = List(A, A, A, A, A, A, A, A, A, A, A, A, A, A, A)

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.163.229