Kotlin secondary constructor prameter


#1

How can i pass two integers to the secondary constructor

    class Test(var name:String){
        
        constructor(age:Int,data:Int):this(data){
            println("$age $data")
        }
        fun display(){
        println("hello world $name")
        }
    }
    fun main(args: Array<String>) {
        var t=Test("john")
        var t1=Test(10,25)
        t.display()
    }

but it gave me the error

     Simplest version.kt

    Error:(8, 39) Type mismatch: inferred type is Int but String was expected
    Warning:(17, 8) Variable 't1' is never used

But after some googling i solved this problem by making one of the parameter as String type. But want to pass those parameters as integer type .How can i achieve that?


#2

What is t1.display() supposed to display in your example?


#3

Convert data to a string when calling the primary constructor:

constructor(age:Int,data:Int):this(data.toString()){

#4

no. I want those parameters as integer


#5

Then you are not making the problem clear enough. Both age and data are integers in my solution. The conversion to String takes place during the primary constructor invocation.


#6

That’s why I asked what t1.display() should display :slight_smile: