The infix Keyword

If you add the infix keyword to a function declaration, you can use that function using infix notation, skipping the parentheses and looking more like the in operator:

private val VOWELS = "[aeiouAEIOU]".toRegex()

infix fun String.disemvowel(replacement: String) = VOWELS.replace(this, replacement)

fun main() {
  println("this is very impolite" disemvowel "*")
}

To “disemvowel” some text is simply to remove the vowels, replacing them with placeholders or just eliminating them outright. Here, we have a disemvowel() extension function on String that removes the English-language vowels (ignoring “y” and “Y” because English is weird). You are welcome to call disemvowel() using regular function notation:

println("this is very impolite".disemvowel("*"))

However, the infix keyword means that we can use this function much like we would use an operator like in:

Regardless of whether you use disemvowel() as a function or as a pseudo-operator, you get a disemvoweled string:

th*s *s v*ry *mp*l*t*

Prev Table of Contents Next

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