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
class Greeter(prefix: String, suffix: String) {
def greet(name: String): Unit =
println(prefix + name + suffix)
}
val greeter = new Greeter("Hello, ", "!")
greeter.greet("Scala developer") // Hello, Scala developer!
class aClass {
var aField : Int = 0;
def this(aValue : Int) = {
this();
this.aField = aValue;
}
}
val myObj=new aClass(1)
myObj.aField
/*
res35: Int = 1
*/
Case Class (You can instantiate case classes without the new keyword:)
case class Point(x: Int, y: Int)
val point = Point(1, 2)
val anotherPoint = Point(1, 2)
val yetAnotherPoint = Point(2, 2)
if (point == anotherPoint) {
println(point + " and " + anotherPoint + " are the same.")
} else {
println(point + " and " + anotherPoint + " are different.")
} // Point(1,2) and Point(1,2) are the same.
if (point == yetAnotherPoint) {
println(point + " and " + yetAnotherPoint + " are the same.")
} else {
println(point + " and " + yetAnotherPoint + " are different.")
} // Point(1,2) and Point(2,2) are different.