emi
emi

Reputation: 2950

Scala complication. Variable reassignment

I'm trying to understand how Scala works. So I typed this code.

var name = "eMmanuel"
val n = name.exists(_.isUpper)

name = "book"

Just looking at it, in my mind, I expect n to be true, I compile this and n: Boolean = true, which is understandable. But in the console I see something strange.

name: String = book
n: Boolean = true
name: String = book

After compilation, first line of results from console tells me name: String = book now, if name is now String = book why is n: Boolean = true? Shouldn't this be false? because after all, it's showing name: String = bookwhich obviously has no capital letter in it!

Upvotes: 0

Views: 302

Answers (1)

mikołak
mikołak

Reputation: 9705

I'm assuming name = book is actually name = "book".

n will have an unchanged value because it is a val. A val gets only evaluated once, on assignment (there are also lazy vals that are evaluated on first dereference). See e.g. here for more information.

In your specific case, it looks like you wanted n to be evaluated each time, which means you need to declare n as a def, i.e.:

def n = name.exists(_.isUpper) 

This will create a no-argument method, evaluated every time you invoke n.

Upvotes: 5

Related Questions