0

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!

emi
  • 2,830
  • 5
  • 31
  • 53
  • Are you actually re-evaluating the second line? Because the result stored in n is not lazy, it will only be calculated once. – danielkza Dec 18 '13 at 12:38

1 Answers1

5

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.

Community
  • 1
  • 1
mikołak
  • 9,605
  • 1
  • 48
  • 70