The Most Underrated Kotlin Function
Introduction to operator functions in Kotlin.
Compared to Java, there are numerous — I say numerous — types of functions in Kotlin. We have extension functions, infix functions, inline functions, higher-order functions, tailrec functions, and lastly, operator functions. Many developers out there use extension functions and higher-order functions but not many understand the usage of operator functions
Understanding operator functions
What is an operator? It is a keyword that is used to do some kind of operation such as arithmetic, logical, and relational.
What is a function? It is a block of executable code that can be called at any time.
So what is an operator function? It is a block of executable code that is invoked by some operator keyword. They must be inside of a class, or a top-level extension function.
A basic example of operator functions
Operator functions must have a receiver class. In other words, they must be inside of a class, or a top-level extension function. Let’s have a basic look at the following code below:
Line number 10 is where the magic happens. times
is a specific operator function which uses the asterisks (*) for its invocation. The receiver class is a String
and it’s allowed just one parameter n: Int
which, for us, is the number of repetitions.
By default, you cannot use the code sampleString * 5
and expect it to work. You will need to define an operator function for this.
The actual power of operator functions
Let’s start by creating a Matrix class and defining some functions and properties that will initialise the matrix.
I have documented the functions so it’s easier to understand. rows
is the actual matrix of the class; it is a two-dimensional double array.
get(Int) operator function
I want to use Matrix class like a 2D Array with superpowers! For example, if I want to access the first row of the Matrix class, Normally I would have to get the property. But that would not be required anymore.
val matrix = matrix {
row(3, 5) // Kotlin-DSL function to add a row
row(-2, 1)
}/* usually */
println(matrix.rows[0][2])/* using get operator function */
println(matrix[0][2])
Instantly, we need our code has become more readable. The first []
after matrix
calls the get(n)
function with n
being 0.
plus(Matrix) operator function
There are some functions and constructors that I haven’t shown the implementation of, but that does affect the understanding.
In the plus()
function, we accept one parameter which is a Matrix
itself. We the plus()
operator is invoked and returns a third Matrix
.
val A = matrix {
row(8, -5)
row(3, -1)
}// invoking the plus() function with the operator
val C = A + matrix {
row(4, 5)
row(0.3, -3.0)
}
Here is the link to the GitHub repository.
I hope you enjoyed reading my article. Thank you! ✌️
Want to connect?My GitHub Profile
My LinkedIn Page