Hello,
I'm quite new to Scala programming language, and was trying something out stucked in my mind while I was following the lecture notes at here.
I think I couldn't really understand how cons operator works, here are some things I tried:
I've created a pseudo-random number generator, then tried to create a list of one random value:
scala> val gen = new java.util.Random
gen: java.util.Random = java.util.Random@1b27332
scala> gen nextInt 3 :: Nil
<console>:7: error: type mismatch;
found : List[Int]
required: Int
gen nextInt 3 :: Nil
^
But it tried to pass List(3) to nextnt method. When i used paratheses, there was no problem
scala> (gen nextInt 3) :: Nil
res69: List[Int] = List(1)
I was curious about the execution order, so i created a function to check it
scala> def pr(i:Int):Int = { println(i); i }
pr: (i: Int)Int
scala> pr(1) :: pr(2) :: pr(3) :: Nil
1
2
3
res71: List[Int] = List(1, 2, 3)
As seen in outputs, execution order is the same as the order of appearance. Then I thought it might be about the 'nextInt' function, then I tried following:
scala> 1 + 2 :: Nil
res72: List[Int] = List(3)
It first executed additionaddition, and after that cons is executed. So here is the question: What is the difference between gen nextInt 3 :: Nil
and 1 + 2 :: Nil
?