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

Scala: How to define a constructor?

Using ‘this()’ you can define a constructor.

Define default constructor

class Employee(id: Int, firstName: String, lastName: String) {

def this() = {
this(0, "no_name", "no_name")
}

}

Define constructor with arguments

class Employee(id: Int, firstName: String, lastName: String) {
def this(id: Int) = {
this(id, "no_name", "no_name")
}

def this(id: Int, firstName: String) = {
this(id, firstName, "no_name")
}
}

Final Employee class looks like below.

class Employee(id: Int, firstName: String, lastName: String) {

def this() = {
this(0, "no_name", "no_name")
}

def this(id: Int) = {
this(id, "no_name", "no_name")
}

def this(id: Int, firstName: String) = {
this(id, firstName, "no_name")
}

def getId = {
id
}

def getFirstName = {
firstName
}

def getLastName = {
lastName
}

override def toString = {
s"id = $id, firstName: $firstName, lastName: $lastName"
}

}

 Examples to define object using constructors.

val emp1 = new Employee()

val emp2 = new Employee(123)

val emp3 = new Employee(123, "Krishna")

val emp4 = new Employee(123, "Krishna", "Gurram")

Find the below working application.

scala> class Employee(id: Int, firstName: String, lastName: String) {
|
| def this() = {
| this(0, "no_name", "no_name")
| }
|
| def this(id: Int) = {
| this(id, "no_name", "no_name")
| }
|
| def this(id: Int, firstName: String) = {
| this(id, firstName, "no_name")
| }
|
| def getId = {
| id
| }
|
| def getFirstName = {
| firstName
| }
|
| def getLastName = {
| lastName
| }
|
| override def toString = {
| s"id = $id, firstName: $firstName, lastName: $lastName"
| }
|
| }
class Employee

scala> val emp1 = new Employee()
val emp1: Employee = id = 0, firstName: no_name, lastName: no_name

scala> val emp2 = new Employee(123)
val emp2: Employee = id = 123, firstName: no_name, lastName: no_name

scala> val emp3 = new Employee(123, "Krishna")
val emp3: Employee = id = 123, firstName: Krishna, lastName: no_name

scala> val emp4 = new Employee(123, "Krishna", "Gurram")
val emp4: Employee = id = 123, firstName: Krishna, lastName: Gurram

 

 

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: How to define a constructor?

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×