Constructor overloading with Kotlin

Viewed 28724

As i have one User class having 2 parameters : first_name, last_name. So my kotlin class with be :

data class User(val first_name:String, val last_name:String)

Now i want a constructor which will accept only first_name, or you can say just one parameter. How can i define it with Kotlin?

I know we can pass default value and in that way we can ignore second parameter, but how can we write multiple constructor?

5 Answers

If you are using data class, then you won't require another constructor. Just pass default value to your last_name parameter. If you are using a normal class then you can have secondary constructor Lets say you have class A

class A(val param:String,val param2:String){
 constructor(val param:String):this(param,"")
}

If you wish manipulate these values you can use init{} block where you can play around your constructor values.

I hope this will help.

This sample of code works fine for me, you can customize them to your need.

data class Booking(
    var user: String,
    var bike: String
){
    constructor(
        user: String,
        bike: String,
        taken_at: String,
        returned_at: String
    ) : this (user, bike)
}
Related