chapter nine

9 Operator overloading and other conventions

 

This chapter covers

  • Operator overloading
  • Conventions: special-named functions supporting various operations
  • Delegated properties

Kotlin has a number of features where specific language constructs are implemented by calling functions that you define in your own code. You already may be familiar with these types of constructs from Java, where objects that implement the java.lang.Iterable interface can be used in for loops, and objects that implement the java.lang.AutoCloseable interface can be used in try-with-resources statements.

In Kotlin, such features are tied to functions with specific names (and not bound to some special interfaces in the standard library, like they are in Java). For example, if your class defines a special method named plus, then, by convention, you can use the + operator on instances of this class. Because of that, in Kotlin we refer to this technique as conventions. In this chapter, we’ll look at different conventions supported by Kotlin and how they can be used.

9.1 Overloading arithmetic operators makes operations for arbitrary classes more convenient

9.1.1 Plus, times, divide, and more: Overloading binary arithmetic operations

9.1.2 Applying an operation and immediately assigning its value: Overloading compound assignment operators

9.1.3 Operators with only one operand: Overloading unary operators

9.2 Overloading comparison operators make it easy to check relationships between objects

9.2.1 Equality operators: equals ("==")

9.2.2 Ordering operators: compareTo ("<", ">", "⇐" and ">=")

9.3 Conventions used for collections and ranges

9.3.1 Accessing elements by index: the "get" and "set" conventions

9.3.2 Checking whether an object belongs to a collection: the "in" convention

9.3.3 Creating ranges from objects: The "rangeTo" convention

9.3.4 Making it possible to loop over your types: The "iterator" convention

9.4 Making destructuring declarations possible with component functions

9.4.1 Destructuring declarations and loops

9.4.2 Ignoring destructured values with "_"