开发者

Scala val and var related question and scala requiring me to assign a value at declaration

I have a variable that I want to declare like:

val foo : Baz

for (s <- barList) {
 if s.tag == "java"
   foo = s
}

Once foo is assigned a value, foo cannot be reassigned. From this perspective foo is of type val and not var. But above is not valid scala code as scala forces to assign a value at the declaration time. Even if I use var, scala forces me to assign a value. Is there a better so开发者_运维百科lution? The reason I would like val is because it results in better performance and val semantics fits in above scenario.


I'd do something like this:

val foo: Baz = barList.find(_.tag == "java").getOrElse( /* provide default here */)


The problem is that you are looking at this from a C perspective - a variable, mutable or not, is just a memory address to place some value in.

In functional languages, though, a variable is a like a named expression (more or less). You declare: From here on, the thing on the left should be considered as it's the thing on the right. Just declaring the variable is an attempt to assign a name to nothingness.

If you, however do not care about such things you can use a var to store the value, update it or whatever you need and the reassign it to a val. Or just modify and use MageeS' solution.


What about

val foo = barList.find(_.tag == "java")


You can use _ to pass a default value to a var (for a val its quite useless):

var foo : Baz = _

for (s <- barList) {
  if s.tag == "java"
   foo = s
}

However, for this particular example, the solution of MageeS is better. If possible, avoid declaring var.

Edit: To address Jean-Phillipe comment. When inside the body of a function, if you cannot assign a reasonable default value. You should use Option. The code becomes:

var foo : Option[Baz] = None

for (s <- barList) {
  if s.tag == "java"
   foo = Some( s )
}

After the loop, foo will still be equal to None if nothing was found, or equal to Some(...) where the dots replace the last element in barList whose tag is "java". You can retrieve this value with foo.get.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜