Reputation: 9143
I'm following a kotlin overloading tutorial here and failing to understand this example:
fun main(args: Array<String>) {
val p1 = Point(3, -8)
val p2 = Point(2, 9)
var sum = Point()
sum = p1 + p2
println("sum = (${sum.x}, ${sum.y})")
}
class Point(val x: Int = 0, val y: Int = 10) {
// overloading plus function
operator fun plus(p: Point) : Point {
return Point(x + p.x, y + p.y)
}
}
When you run the program, the output will be:
sum = (5, 1)
Specifically, the return line:
return Point(x + p.x, y + p.y)
How is this line working? Why is it x + p.x
- where are those values coming from?
Upvotes: 0
Views: 62
Reputation: 30695
You have a class class Point(val x: Int = 0, val y: Int = 10)
which has x
and y
properties. Consider operator fun plus(p: Point) : Point
as a simple function of class Point
that receives another Point
as a parameter, creates another instance of Point
adding x
and y
coordinates of current and another point p
and returns it. So in that function you have access to the properties of current instance of Point
and another Point
instance: x
and y
.
We can read the expression var sum: Point = p1 + p2
as the following:
take p1
as a current instance of Point
, add p2
as another instance of Point
. In this case plus
function is called on the p1
instance with passing p2
as the argument of that function. When the function returns variable sum
will refer to the instance of newly created Point
.
Upvotes: 1