Comparison with Python
import kotlin.math.hypot
class Point(var x: Double, var y: Double) {
fun distance() = hypot(x, y)
fun distanceTo(p: Point) = hypot(x - p.x, y - p.y)
}
from math import hypot
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self):
return hypot(self.x, self.y)
def distanceTo(self, p):
return hypot(self.x - p.x, self.y - p.y)
Before progressing any further, spend a few minutes comparing the two
implementations of Point that you created in Task 12.1. You should have
code resembling that shown above.
Here are the key differences:
-
The Kotlin class requires fewer lines of code, due to its very compact way of defining properties and primary constructor, and the use of expression body syntax when defining the methods.
-
The Kotlin class requires that types be specified for the properties. This is not required for Python (although if you wanted, you could specify that
xandyought to be of typefloatusing Python’s type hinting feature). -
The Python constructor has an explicit parameter
self, appearing before the parameters representing point coordinates, which refers to the object being created. Similarly, thedistance()anddistanceTo()methods both have aselfparameter to represent the object on which the method is being called.Methods in Kotlin classes do not use an explicit parameter for such a purpose, although you are free to use the special variable
thisas an implicit reference to the object. -
When referring to the fields
xandyin the Python class, you are required to useselfas a prefix: i.e, you must refer to the fields asself.xandself.y.You do not need to use any prefix in the Kotlin class, although you can be more explicit and refer to the properties as
this.xandthis.yif you really want to.