Example: Dividing a String

By default, in Kotlin, this fails with a compile error:

fun main() {
  val pieces = "This is a reasonably long string" / 3
}

Kotlin does not know how to divide a String by an Int. However, we can teach Kotlin to do this, by way of implementing a div() extension function on String:

operator fun String.div(count: Int) = this.chunked((this.length / count) + 1)

fun main() {
  println("This is a reasonably long string" / 3)
}

Just as we need to override a function that is declared in a supertype, we need to add the operator keyword to a function whose name is used by Kotlin as the implementation of an operator. Here, div() is the function that Kotlin maps / to. So, our div() extension function allows us to divide a String by an Int.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.