Search code examples
kotlinconstructor

kotlin: "unresolved reference" in secondary constructor


i am very new to kotlin, and maybe this might be a silly question but why using a variable defined in a secondary parameter gives an error of "unresolved reference" when i try to print it while the same does not happen in case of primary constructor

fun main(args: Array<String>){    
    var stud= Student("Yash", 10)    
}

class Student(name: String) {
    init {
        println("name is $name")
    }

    constructor(n: String, Id: Int): this(n) {
       println("name is $n")
       println("id is $id")
    }
}

Solution

  • Parameter id is small letter,but you are try to print capital letter Id, change like this its working now

    constructor(n: String, id: Int)

    fun main(args: Array<String>){
    var stud= Student("Yash", 10)
    }
    
    class Student(name: String) {
    init {
        println("name is $name")
    }
    
    constructor(n: String, id: Int): this(n) {
        println("name is $n")
        println("id is $id")
    }
    }