The Artima Developer Community
Sponsored Link

Programming in Scala Forum
Understanding 'var' and 'val'

2 replies on 1 page. Most recent reply: Mar 15, 2018 11:32 PM by jinf Fei

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
akash dhasade

Posts: 1
Nickname: akash58
Registered: Jun, 2017

Understanding 'var' and 'val' Posted: Jun 28, 2017 4:11 AM
Reply to this message Reply
Advertisement
var defines a mutable object and val defines an immutable object. So as suggested in the book if I define ->
import scala.collection.mutable.Set
val set = Set(1,2,3)
set += 4

It works. Since I have imported a mutable set.

Similarly if I would do as follows:
import scala.collection.immutable.Set
var set = Set(1,2,3)
set += 4

It should give me an error because my set is immutable but it doesn't!

Why??


Guke Huang

Posts: 1
Nickname: guke
Registered: Dec, 2017

Re: Understanding 'var' and 'val' Posted: Dec 19, 2017 7:31 PM
Reply to this message Reply
You misunderstand the immutable object that val refers to. The keyword val defines a object that can not be reassigned, but it's just a refrence. That means val can not refer to others.

jinf Fei

Posts: 3
Nickname: jm8371
Registered: Mar, 2018

Re: Understanding 'var' and 'val' Posted: Mar 15, 2018 11:32 PM
Reply to this message Reply
Yes, you can think that val variable point a "box", you can put a apple into box or put a bannel into box. But you can not change the "box".

So you can change Set context but you can not change the Set object.

Flat View: This topic has 2 replies on 1 page
Topic: Checksum Previous Topic   Next Topic Topic: Typos in 3rd Edition

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use