the differences between val var and def

I was wondering about the differences between val, var and def in Scala, and these are what I found :

  • def

    1. Immutable
    2. Lazily evaluated (Evaluated by Name)
    scala> def x = 1+2
    x: Int
    scala> x = 4
    
    
    <console>:11: error: value x_= is not a member of object $iw
           x = 4  //can't reassign x because immutable
           ^
    
    
    scala> x        //Lazily evaluated 
    res0: Int = 3
    
    
    
  • val

    1. Immutable
    2. Eagerly/immediately evaluated (evaluated by value)
    scala> val x = 1+2 
    x: Int = 3    // Eagerly/immediately evaluated
    
    
    scala> x = 4    //can't reassign x because immutable
    <console>:11: error: reassignment to val
       x = 4
         ^
    
    
    
  • var

    1. mutable
    2. Eagerly/immediately evaluated (evaluated by value)
    scala> var y = 3
    y: Int = 3  // Eagerly/immediately evaluated
    
    
    scala> y = 2    //can reassign value
    y: Int = 2
    

Hope these help,,thanks

comments powered by Disqus