Introduction
The most of you are probably familiar with the builder pattern. I used this pattern a couple of times in Java later on with the @Builder annotation from the Lombok project. I am aware of the fact that the annotations of Lombok project are also usable in Kotlin. This is just for fun or when you are not using Lombok for what reason suits you.
the code
For this example I used a data class called Address. I am aware that it lacks some fields but that is not important in this explanation. Ok, lets get down to it:
//The class members that will contain the data.
val addressLine1: String,
val addressLine2: String = "",
val city: String,
val zip: String,
//The builder class
class Builder {
private lateinit var addressLine1: String
private var addressLine2: String = ""
private var city: String = ""
private var state: String = ""
//The assignment to the class members.
fun addressLine1(addressLine1: String) = apply { this.addressLine1 = addressLine1 }
fun addressLine2(addressLine2: String) = apply { this.addressLine2 = addressLine2 }
fun city(city: String) = apply { this.city = city }
fun country(country: String) = apply { this.country = country }
//The build method we need to call.
fun build() = Address(
addressLine1,
addressLine2,
city,
state,
country
)
}
//The instanciation of the Adress class.
val address:Address = Address
// calling the builder class.
.Builder()
//filling the fields with data.
.addressLine1("Address1")
.addressLine2("Address2")
.city("City")
.country("Country")
//calling the build method
.build()
// Voila data
println(address.addressLine1)
Conclusion
As allways, with a new way you have to get used to the fact that things are different. If you are new to Kotlin this might look magical to you. At least it did to me. Now I am working with Kotlin for a while I am used to the syntax. I am capable of doing stuff in Kotlin I did not think I would ever do.
Have fun!
Geen opmerkingen:
Een reactie posten