Search code examples
functionkotlinclassmethodsreference

how to reference arguments with parameters in a function?


class Score(
    val score:Int
){
    fun PersonalScore(){
        println(score)
    }

}
fun comPare(a: Int, b: Int, c: Int): Int{
    var max = a
    if(max < b) max = b
    if(max < c) max = c
    println("The best score is $max")
    return max
}
fun main() {
    val score1 = Score(10)
    val score2 = Score(4)
    val score3 = Score(7)
    comPare(score1, score2, score3)  //this line is error

P/s: I'm a beginner and I don't know how to fix it. Please give me some guide, I'll be very grateful for your help. Thank you guys so much!!

can understand more deeply and practice more and more


Solution

  • You defined the comPare function to take Int parameters. Your Score class is not an Int. It is a Score. It has a property inside it that is an Int. You must be very precise. If the parameter is defined as Int, you have to pass it an Int, not a Score.

    So there are two different (mutually exclusive) solutions.

    1. Pull the Int parameters out of your Score instances when passing them to the comPare function.
    2. Change the comPare function to take Score parameters instead of Int parameters, and read the values out of the Score instance inside this function.

    1:

    fun main() {
        val score1 = Score(10)
        val score2 = Score(4)
        val score3 = Score(7)
        comPare(score1.score, score2.score, score3.score)
    } 
    

    2:

    fun comPare(a: Score, b: Score, c: Score): Int{
        var max = a.score
        if(max < b.score) max = b.score
        if(max < c.score) max = c.score
        println("The best score is $max")
        return max.score
    }