Scala has three ways to define a variable, method name or object:
- def defines a method
- val defines a fixed value (which cannot be modified - these are like Java final variables)
- var defines a variable (which can be modified later). These are discouraged in Scala since they are mutable and are indicative that the program is using an imperative style of programming.
class Person(val name:String,var age:Int )
def person =new Person("Kumar",12)
person.age=20
println(person.age)
These lines of code give output as 12. ALWAYS. The reason is that "def person" creates a function definition instead of an object. Thus each time you write person in the code, it refers to a brand new Person object created by the person method. This happens in the assignment as well as the println code!
args.foreach(println)
These lines of code give output as 12. ALWAYS. The reason is that "def person" creates a function definition instead of an object. Thus each time you write person in the code, it refers to a brand new Person object created by the person method. This happens in the assignment as well as the println code!
Another example from the "Programming in Scala, 2nd Edition" - If a function
literal
consists of one
statement that takes a single argument, you need not explicitly
name and specify
the argument. Thus, the following code works and println looks like the name of variable in this case:
No comments:
Post a Comment