Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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 x and y ought to be of type float using 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, the distance() and distanceTo() methods both have a self parameter 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 this as an implicit reference to the object.

  • When referring to the fields x and y in the Python class, you are required to use self as a prefix: i.e, you must refer to the fields as self.x and self.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.x and this.y if you really want to.