I have been trying to add a secondary constructor to my heelo world program in kotlin. The following is my code. (I used online kotlin ide https://try.kotlinlang.org/#/Examples/Hello,%20world!/Simplest%20version/Simplest%20version.kt)
class Test(var name:String){
constructor(age:Int,data:Int){
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 shows me the following error
Simplest version.kt
Error:(8, 4) Primary constructor call expected
Warning:(18, 8) Variable 't1' is never used
After some googling i resolved the error. changing the second parameter of secondary constructor to string type and adding :this(data) solved the problem .The following is the resolved code
class Test(var name:String){
constructor(age:Int,data:String):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 the problem is i want to pass two integer values to the secondary constructor.I tried the following,but it gave this error
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 this 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
How do i achieve this?. How can I pass two integer variable to the secondary constructor?