will 'val' produce mutable data? [duplicate] - scala

This question already has answers here:
Why is it possible to declare variable with same name in the REPL?
(2 answers)
Closed 7 years ago.
In REPL when we type the below command
scala> val p = 1 << 1
p: Int = 2
again
scala> val p = 1 << 2
p: Int = 4
my question is , I read that val is immutable . but in this case the value is changing right . Well can someone tell me why . is this really an example of mutatating . Please help

This behaviour appears in REPL only. If you try to define val twice in Scala code you'll get compilation error. In REPL second definition of val just shadows previous value of p

yep, as nyavro said, in the REPL you can override vals. Just think that in IDE if you make a mistake typing a value you can fix, in the REPL how would you fix? you would need to close the session?

Related

'for' loop inside the code snippet not understood [duplicate]

This question already has answers here:
Confused with the for-comprehension to flatMap/Map transformation
(5 answers)
in scala why does for yield return option instead of string
(3 answers)
Is for-yield-getOrElse paradigmatic Scala or is there a better way?
(1 answer)
Closed 3 years ago.
I have below piece of code, which is printing: Some(600) as output.
Its not understood how the addition is happening inside 'for' loop.
In below, its confusing whats happening inside the code block of 'for' loop and how the variable 'y' is being calculated. Can someone please help?
object TestObject extends App
{
def toInt(s: String): Option[Int] = {
try
{
Some(Integer.parseInt(s.trim))
}
catch
{
case e: Exception => None
}
}
val y = for
{
a <- toInt("100")
b <- toInt("200")
c <- toInt("300")
} yield a + b + c
println(y)
}
In Scala this is called a for-comprehension.
toInt wraps the value in an Option which is extracted by <- and assigned to a and so on.
If one of the Option is None the result would be None
yield always returns its last statement, in your case: a + b + c
And so the result is Some(600).
See the documentation here: https://docs.scala-lang.org/tour/for-comprehensions.html
From inside the for loop, toInt method is being called which returns an Option[Int]. Now what for loop does is to simply open the Option container and assign variable a with value of 100. On similar lines, variables b and c are assigned value of 200 and 300.
And in the end the yield statement adds the values a,b and c and puts it back in the Option container.
Please refer to https://docs.scala-lang.org/tutorials/FAQ/yield.html and https://alvinalexander.com/scala/scala-for-loop-yield-examples-yield-tutorial

Is there a way in scala for printing the size of a list beetween a function chaining? [duplicate]

This question already has answers here:
how to keep return value when logging in scala
(6 answers)
Closed 5 years ago.
Of course, I could break this code by extracting the list after the filter or the map function and print the size. But for the sake of learning i am wondering whether there is a nicer solution where i could keep this function chaining.
listOfSomething.filter(condition).map(e => e.mapToSomeOther).mkString(DELIMITER)
There is, afaik, no methods on immutable sequences that have side effects, but you can enrich the API with side-effect methods (I don't recommend this) like so:
scala> implicit class PrintSize[T](xs: List[T]){ def printSize = { println(xs.size); xs} }
defined class PrintSize
scala> List(1, 2, 3, 4, 5, 6, 7).filter(_ > 3).printSize.map(_ * 2).mkString(",")
4
res2: String = 8,10,12,14
Your first suggestion about extracting temporary results is much better, because you can do your side effects after or before the entire computation.

Why does not ; equivalent to the eol? [duplicate]

This question already has answers here:
toList on Range with suffix notation causes type mismatch
(2 answers)
Closed 6 years ago.
Here is the code that compiles as intended
def coarse_grained: Int = {
def fib: Int = List(1,2) sum ;
fib
}
and one which does not
def coarse_grained: Int = {
def fib: Int = List(1,2) sum
fib
}
The only difference is ; after the sum.
As you know, List(2,6,9).drop(1) can also be written as List(2,6,9) drop 1. In fact, it can also be written like this.
List(2,6,9) drop
1
The compiler keeps looking for the final argument, even past a newline. So if you want to do this List(1,2).sum like this List(1,2) sum, you'll need to use the semicolon ; to tell the compiler to stop looking for the final argument. It's not coming.

How can I overwrite the values of a tuple in scala? [duplicate]

This question already has answers here:
In Scala, how can I reassign tuple values?
(2 answers)
Closed 7 years ago.
I tried to overwrite the tuple values in scala using
val item = (1,'A',1);
item._1=2;
But I got an error 'reassignment to value'. Then I used stackoverflow "In Scala, how can I reassign tuple values?" and found the following solution:
val item = (1,'A',1);
item = item.copy(_1,2);
But I am getting the same error 'reassignment to value'. I tried with both val and var keyword.
A tuple in Scala is immutable, i.e. you can't change it values.
The second version goes in the correct direction, but you should use it like this:
var item = (1, 'A',1);
item = item.copy(_1 = 2);
I.e. you make it a var not a val so you can reassign it.

Idiomatic way of extracting lists from a list of tuples [duplicate]

This question already has answers here:
Scala: How to convert tuple elements to lists
(5 answers)
Closed 8 years ago.
Is there a concise way of performing the following mapping in Scala?
val listOfTuples: List[Tuple2[Foo, Bar]] = ???
val (foos, bars) = listOfTuples // foo:List[Foo], bar:List[Bar]
I have seen others map the List[Tuple[X, X]] onto a List[List[X]] and then transpose the list, although this only works with tuples composed from homogeneous type parameters.
You should use method unzip like this:
val (foos, bars) = listOfTuples.unzip
There is also a method unzip3 for collections of Tuple3.
And if for arity 3 to 22 you could do this with product-collections:
val foos = listOfTuples._1
val bars = listOfTuples._2