android – Constructor overloading with Kotlin-ThrowExceptions

Exception or error:

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?

How to solve:

You can define extra constructors in the class body

data class User(val firstName: String, val lastName: String) {

    constructor(firstName: String) : this(firstName, "")

}

These ‘secondary constructors’ have to call through to the primary constructor or a different secondary constructor. See the Official documentation on constructors.

So, in effect this is the same as just a primary constructor with default argument, which would be the idiomatic way to go.

data class User(val firstName: String, val lastName: String = "")

###

I hope this will help you

class Person(val name: String, val age: Int = 0) {
    override fun toString(): String {
        return name + " is " + age + " years Old"
    }
}

fun main(args: Array<String>) {
    var person = Person(name = "vignesh")
    var personNew = Person("vignesh", 23)
    println(person.toString())
    println(personNew.toString())
}

Output

vignesh is 0 years Old

vignesh is 23 years Old

###

A class in Kotlin can have a primary constructor and one or more secondary constructors. The primary constructor is part of the class header: it goes after the class name (and optional type parameters).

class Person constructor(firstName: String) {
}

If the primary constructor does not have any annotations or visibility modifiers, the constructor keyword can be omitted:

class Person(firstName: String) {
}

Note that parameters of the primary constructor can be used in the initializer blocks. They can also be used in property initializers declared in the class body:

class Customer(name: String) {
    val customerKey = name.toUpperCase()
}

You can also follow this link as per your need : Kotlin

###

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.

Leave a Reply

Your email address will not be published. Required fields are marked *