I am very new to Scala, so this question can be very naive.
I have a list like List[Int] = List(0, 3, 6, 12, 14, 15, 16, 17) . I am trying to create a list like this [(0,3),(3,6),(6,12)..] and so on. So far this is what I tried:
val l1= List(0, 3, 6, 12, 14, 15, 16, 17) var l2=scala.collection.mutable.ListBuffer[(Int,Int)]() l1.zipWithIndex.slice(0,l1.length-1).foreach(x=>{val newval=(x._1,l1(x._2+1)); l2+=newval})
Two questions here:
- If I do not use
val newval , i.e. I will try to execute l1.zipWithIndex.slice(0,l1.length-1).foreach(x=>l2+=(x._1,l1(x._2+1))) , the compiler says: <console>:10: error: type mismatch; found : Int required: (Int, Int) l1.zipWithIndex.slice(0,l1.length-1).foreach(x=>l2+=(x._1,l1(x._2+1))) <console>:10: error: type mismatch; found : Int required: (Int, Int) l1.zipWithIndex.slice(0,l1.length-1).foreach(x=>l2+=(x._1,l1(x._2+1))) . Why is this? - What is the way to do this without a mutable listbuffer?
immutability list scala functional-programming
rivu
source share