Class
A Scala class is a template for Scala objects. A class can contain information about:
Fields
Constructors
Methods
Superclasses (inheritance)
Interfaces implemented by the class
1
class Greeter(prefix: String, suffix: String) {
2
def greet(name: String): Unit =
3
println(prefix + name + suffix)
4
}
5
val greeter = new Greeter("Hello, ", "!")
6
greeter.greet("Scala developer") // Hello, Scala developer!
Copied!
1
class aClass {
2
var aField : Int = 0;
3
def this(aValue : Int) = {
4
this();
5
this.aField = aValue;
6
}
7
}
8
9
val myObj=new aClass(1)
10
myObj.aField
11
​
12
/*
13
res35: Int = 1
14
*/
Copied!

Case Class (You can instantiate case classes without the new keyword:)

1
case class Point(x: Int, y: Int)
2
val point = Point(1, 2)
3
val anotherPoint = Point(1, 2)
4
val yetAnotherPoint = Point(2, 2)
5
if (point == anotherPoint) {
6
println(point + " and " + anotherPoint + " are the same.")
7
} else {
8
println(point + " and " + anotherPoint + " are different.")
9
} // Point(1,2) and Point(1,2) are the same.
10
if (point == yetAnotherPoint) {
11
println(point + " and " + yetAnotherPoint + " are the same.")
12
} else {
13
println(point + " and " + yetAnotherPoint + " are different.")
14
} // Point(1,2) and Point(2,2) are different.
Copied!
​
Last modified 1yr ago