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!

1
  • Are you actually re-evaluating the second line? Because the result stored in n is not lazy, it will only be calculated once. Commented Dec 18, 2013 at 12:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.