plus運算子

把+運算子的方法覆寫。

1
2
3
4
5
class Emp (val empId: String, val salary: Int){
    operator fun plus(other: Emp): Emp {
        return Emp("", other.salary + this.salary)
    }
}

2個員工薪水相加。

1
2
3
4
5
6
fun main() {
    val emp1 = Emp("001" , 50000)
    val emp2 = Emp("002", 30000)
    val sum = emp1 + emp2
    println(sum.salary)
}
80000

results matching ""

    No results matching ""