Home » Blog » Operator Functions

Operator Functions

Certain functions can be “upgraded” to operators, allowing their calls with the corresponding operator symbol.

  • This takes the infix function from above one step further using the operator modifier.
  • The operator symbol for times() is * so that you can call the function using 2 * “Bye”.
  • An operator function allows easy range access on strings.
  • The get() operator enables bracket-access syntax.
operator fun Int.times(str: String) = str.repeat(this)       
println(2 * "Bye ")                                          

operator fun String.get(range: IntRange) = substring(range)  
val str = "Always forgive your enemies; nothing annoys them so much."


Leave a Reply

Your email address will not be published.