Classes in Scala
Scala Tutorial
Classes in Scala are declared using a syntax which is close to Java’s syntax with one important difference is that classes in Scala can have parameters.
If no constructor is defined, a class has a default constructor which takes no arguments.
The below class, SimpleClass has a primary constructor which is in the class signature (name: String, age: Int)
.
/**
* Classes in Scala are declared using a syntax which is close to
* Java's syntax with one important difference is that classes in
* Scala can have parameters.
*
* This SimpleClass class takes two arguments: name and age.
* These arguments must be passed when creating an instance of
* class SimpleClass as follows: new SimpleClass("John", 30).
*/
class SimpleClass (name: String, age: Int) {
def showName() = name
def showAge() = age
}
The SimpleClass class takes two arguments and these arguments must be passed when creating an instance as follows:
new SimpleClass("John", 30)
A class can inherit from multiple traits but only one abstract class.
Methods without arguments
We don’t need to put an empty pair of parenthesis after method name — removing empty pair of parenthesis is perfectly doable in Scala as follows:
def showName = name
def showAge = age
Supper-class
All classes in Scala inherit from a super-class.
When no super-class is specified, scala.AnyRef is implicitly used.
Classes can only have one super-class but many mixins (using the keywords extends
and with
respectively).
What can’t be done with Classes?
Public access modifier is not allowed — Scala class is public by default.
Differences and Similarities with Java
Differences
- Classes in Scala cannot have static members.
- “public” access modifier is not allowed.
- Classes are public by default — Java’s default modifier i.e. “protected” has visibility only within its own package.
- Classes can have parameters.
- Can have multiple public classes in a Scala source file — Unlike Scala, Java source file can have only one public class.
- There is no need to match the source filename with the public class name.
- We must initialize with some value to variables because we cannot define a variable with no value!
Similarities
- Like Java, classes can be instantiated using the new construct.
- There can be many “instances” (or “objects”) of the same class.
Scala Exercises: https://github.com/SenthilNayagan/scala-tutorial