I want to understand better the following issue. When should i use var and when val?
I know that there is a rule of thumb in Scala that we should use val.
For primitive types it's easy - we should use var only if we change a variable in a loop.
My first question is if there any better way to do that in Scala:
var sum = 0
while (condition) sum = sum + something
return sum
But same and more complicated is for collections.
- We have the mutable or immutable collections
- We have var and val for the pointers.
I want to ask for each of the following if it's make sense (means could be, but not necessarily good practice), and when should we use each of the following options (what is good practice):
- val mutable collection
- var mutable collection
- val immutable collection (can't be)
- var immutable collection
I also want to ask if changing a collection means to change it's pointer or it's elements, or both. Take a list for example. If I add an element I did a change. But what if I just want to update an element?
The reason I'm asking this question is that when we need to solve common problems, we need to change the collection and we can't use immutable val.
var list = List(1,2,3)
// this will not save the list with changes
while (condition) list :+ some_integer
return list
This topic is confusing for me in Scala.
I would appreciate if someone can make this topic more clear. Thanks.
I want to understand this topic better. In others languages it's quiet clear, but in Scala it's a bit confusing.
In your example code:
How one might do this without
var
really depends on whatcondition
is. We can't give you a one-size-fits-all answer.But I'll give you one specific example. Suppose we have an imperative method
getNext()
that returns anInt
, and we want to stop summing once it returns a-1
. In Java one might write:In Scala I would write:
here I'm using higher-order methods such as
continually
andtakeWhile
. If the shape of the problem were different, different higher-order methods might be the right ones.As an aside, note that I did not use
return
. 99% of Scala code never usesreturn
at all.