Introduction to Scala Part2 : Collections
Bubu
6,426 views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Traversable : Conversion
- Operations:
- toArray,
- toList,
- toIterable,
- toSeq,
- toIndexedSeq,
- toStream,
- toSet,
- toMap
- Goal: turn a Traversable collection into something more specific.
All these conversions return their receiver argument unchanged if the run-time type of the collection already matches the demanded collection type. For instance, applying toList to a list will yield the list itself.
> List(1, 2, 4).toArray
res0: Array[Int] = Array(1, 2, 4)
convert Iterable -> List
convert List -> Iterable
convert Seq -> List
convert List -> Seq
convert Array -> List
convert List of Int -> Array of Int
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package fp101.tp02.collections
import scala.reflect.ClassTag
object ExerciceConversion {
/**
*
* Simples conversions
*
*/
def fromIterableToList[T](i: Iterable[T]): List[T] = ???
def fromListToIterable[T](l: List[T]): Iterable[T] = ???
def fromSeqToList[T](s: Seq[T]): List[T] = ???
def fromListToSeq[T](l: List[T]): Seq[T] = ???
def fromArrayToList[T](a: Array[T]): List[T] = ???
/**
* Note:
*
* To create a generic method (instantiating an array of T where T is a type parameter),
* It is more difficult because of the implementation of Array in Java that had runtime-safe arrays before it had compiletime parametric polymorphism.
*
* Scala needs at runtime to have information about T, in the form of an implicit value of type ClassTag[T]
*
* def fromListToArray[T](l: List[T])(implicit ev: ClassTag[T]): Array[T] = l.toArray
Enter to Rename, Shift+Enter to Preview