Scala: Field And Method

Reading Time: 3 minutes

In this blog, we will discuss about Scala fields and methods. As we know that fields in any language used to store the information and methods are use to define the behavior of the object. Let’s discuss more about both of them in detail.

What are fields in Scala?

Fields are basically keeping the state of an object. Unlike in Java, Scala fields are of two types i.e Mutable fields and immutable fields. So we can declare mutable fields by using the keyword var and immutable fields by using the keyword val

What are immutable fields in Scala?

In this paragraph, we will discuss more about immutable fields. Immutable means that you can’t change (mutate) your variables. It means you cannot reassign the value once you initialize it. It is the best practice to use always immutable fields because it won’t lead to concurrency issues. val is the keyword used to define immutable fields. Below is an example of how to define an immutable field in Scala.

Now let’s see the byte code representation of the above example and what compiler do when we define any field with val keyword.

Compiler compiles the immutable field into

  • private final field
  • public getter method

What are mutable fields in Scala?

In this paragraph, we will discuss more about mutable fields. Mutable means that you can change (mutate) your variables. It means you can reassign the value once you initialize it. It is not recommended to use mutable fields because it can lead to concurrency issues and anyone can change the state of the field. var is the keyword used to define mutable fields. Below is an example of how to define a mutable field in Scala.

Now let’s see the byte code representation of above example and what compiler do when we define any field with var keyword.

Compiler compiles the immutable field into

  • private field
  • public getter method
  • public setter method

What are methods in Scala?

As we know that Scala is a functional programming language. It contains both functions as first-class values and methods. However, functions are an object which is initialized in a variable. And methods start with the ‘def‘ keyword followed by the method name, parameter list and method body with the return value. The parameters and type annotation in a method declaration are optional and method body declared after the equal sign. Below is an example of how to define methods in Scala.

Thank you for reading this blog. In further blogs, I will discuss more topics in Scala.

Knoldus-blog-footer-image