Sunday, December 4, 2016

Scala idiosyncrasies

Scala is full of idiosyncracies and by writing some of these out here I am hoping it will save someone else the time. I will keep updating this post as I find new ones:

Scala idiosyncrasy # 1:  Iterator.size is not reliable. 

Consider the following lines

  val a: Iterator[Int] = Iterator(1, 2, 3)  
  val b: List[Int] = List(1,2,3)  

A test kept failing because I tried to use Iterator.size in my code instead of List.size. Then I learned that the size of the iterator is computed as the number of entries left to the end of the list. A better way is to use convert the Iterator to a List and then compute its size. Here is an example

  object Solution extends App {  
  val a: Iterator[Int] = Iterator(1,2,3)  
  println(" size of iterator a " + a.size)  
  println(" size of iterator a " + a.size)  
  val b: List[Int] = List(1,2,3)  
  println(" size of list b " + b.size)  
  println(" size of list b " + b.size)  
 }  

Answer:
  size of iterator a 3
  size of iterator a 0
  size of list b 3
  size of list b 3

So there, I learned something about Scala today 

To be continued...

2 comments: