How to implement Builder pattern in Kotlin?


In object-oriented programming, the creation of objects is very easy via constructors when the object definitions are simple, but sometimes, it may so happen that the constructors need more variables or functions in order to initialize an object. In such cases, the "builder pattern" comes into picture which helps programmers to create small units of different objects and create a final object.

  • A builder pattern provides an API to construct an object step- by-step.

  • Builder patterns are particularly useful when objects need to be created dynamically.

Note that it is not recommended to use builder patterns in Kotlin because we can get the same feature using default and named arguments.

In this article, we will take a simple example and demonstrate how we can implement a design pattern using Kotlin.

  • Create a small builder object, which can be built in the main class and the builder class should have a public constructor .

  • Construct an object using multiple pieces; some variables can be set using getter, setter and some via constructor.

  • The builder design pattern provides an API to create an object. We are creating build() to build the actual required object. We can name it differently whatever we need.

  • The main class constructor will take the builder object as a parameter.

Example

class myBuilder{
  private var Name:String? = null

   fun setName(Name:String){
      this.Name = Name
   }
   fun getName():String?{
      return this.Name
   }
}

class myClass{
   var m:myBuilder
   constructor(myBuilder:myBuilder) {
      this.m = myBuilder
   } // implementing the builder class
   fun build():String{
      return ("This is the example of the builder pattern")
   }
}

fun main(args: Array<String>) {
   var myBuilder = myBuilder()
   myBuilder.setName("TutorialsPoint")

   // passing small unit of objects to create
   // another object step-by-step. This can be
   // applied to many class variable
   var mainObj = myClass(myBuilder)
   println(mainObj.build())
}

Output

Once executed, the code will generate the following output

This is the example of the builder pattern

Updated on: 23-Nov-2021

722 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements