Auxiliary Constructor Usages Scala

Sudarshan Kasar
1 min readJan 5, 2021

--

An Auxiliary constructor is a method with this name, which is used to create an instance without passing all the required parameters.

class Student(id: Int,name: String) {
def this(id: Int) {
this(id,“Name”)
println(“auxiliary constructor”)
}
}

The object can be created by passing only id i.e new Student(10) or by passing id and name i.e. new Student(10, “sudarshan”)

Use case

Consider a repository class RepoClass that takes 2 arguments database configuration, entity info. And this class can create database configuration object based on entity info.

class RepoClass(dbConfig: DataBaseConfiguration, entity: Entity){…}

Now Class1 service layer class can create and pass database configuration, entity, so we are good there, though the RepoClass class can derive database configuration by the entity, this class wants to override it, so we are good here. new RepoClass(new DBConfig, new SomeEntity)

Another class Class2 service layer class doesn’t have enough information for database configuration, but can pass entity now it can pass only entity and database configuration can be derived by the entity.

new RepoClass(new SomeEntity)

Conclusion — code reusability

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sudarshan Kasar
Sudarshan Kasar

No responses yet

Write a response