Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Scala: Statements in the class body gets executed while initializing an instance

 If a Class body has any statements, then those gets executed while initializing an object.

class Point(x : Int, y : Int){
println("Initializing point instance")
println(s"x = $x, y = $y")

def getX() = {
x
}

def getY() = {
y
}

override def toString() = {
s"x = $x, y = $y"
}
}

When you define an instance of Point, two println statements which are part of Point class gets executed. These are similar to initializer blocks in Java.

 

scala> class Point(x : Int, y : Int){
|
| println("Initializing point instance")
| println(s"x = $x, y = $y")
|
| def getX() = {
| x
| }
|
| def getY() = {
| y
| }
|
| override def toString() = {
| s"x = $x, y = $y"
| }
| }
class Point

scala> val p1 = new Point(10, 20)
Initializing point instance
x = 10, y = 20
val p1: Point = x = 10, y = 20

scala>

scala> val p1 = new Point(1, 2)
Initializing point instance
x = 1, y = 2
val p1: Point = x = 1, y = 2

 

Statements in the class body is used to validate instance properties.

 

For example, I want to restrict Point to take only non-negative values.

class Point(x : Int, y : Int){
println("Initializing point instance")
println(s"x = $x, y = $y")

if ( x 0 || y 0 ) {
throw new IllegalArgumentException("x and y must be >= 0")
}

def getX() = {
x
}

def getY() = {
y
}

override def toString() = {
s"x = $x, y = $y"
}
}

When you try to initialize Point instance with negative values, you will get java.lang.IllegalArgumentException.

scala> class Point(x : Int, y : Int){
| println("Initializing point instance")
| println(s"x = $x, y = $y")
|
| if ( x 0 || y 0 ) {
| throw new IllegalArgumentException("x and y must be >= 0")
| }
|
| def getX() = {
| x
| }
|
| def getY() = {
| y
| }
|
| override def toString() = {
| s"x = $x, y = $y"
| }
| }
class Point

scala>

scala> val pi = new Point(10, -20)
Initializing point instance
x = 10, y = -20
java.lang.IllegalArgumentException: x and y must be >= 0
... 33 elided

scala> val pi = new Point(-10, 20)
Initializing point instance
x = -10, y = 20
java.lang.IllegalArgumentException: x and y must be >= 0
... 33 elided

scala> val pi = new Point(-10, -20)
Initializing point instance
x = -10, y = -20
java.lang.IllegalArgumentException: x and y must be >= 0
... 33 elided

scala> val pi = new Point(10, 20)
Initializing point instance
x = 10, y = 20
val pi: Point = x = 10, y = 20



 

 

Previous                                                    Next                                                    Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Scala: Statements in the class body gets executed while initializing an instance

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×