Main navigation

Learning Kotlin: Operators don't need to mean one thing

Submitted by Robert MacLean
on Tue, 07/31/2018 - 21:59

More Information

This is the 18th post in a multipart series.
If you want to read more, see our series index

Following on from the previous post we looked at operators and being able to use them yourself by implementing the relevant operator methods. The first part I want to cover in this second post is the Unary operators +, -, and !.

When I was learning this, the term unary jumped out as one I did not immediately recognise, but a quick Wikipedia read it became clear. For example, if you use a negative unary with a positive number, it becomes a negative number... It is primary school maths with a fancy name.

One thing to remember about operators is it is totally up to you what they mean, so, for example, let's start with a simple pet class to allow us to define what type of pet we have.

packageblogcode

enumclass animal {

dog,

cat

}

dataclass pet(val type: animal);

fun main(args: Array<String>){

val myPet = pet(animal.dog)

println(myPet)

}

this produces pet(type=dog)

Now, maybe in my domain, the reverse of a dog is a cat, so I can do this to make this reflect my domain:

packageblogcode

enumclass animal {

dog,

cat

}

dataclass pet(val type: animal){

operatorfun not(): pet =when(this.type){

animal.cat-> pet(animal.dog)

animal.dog-> pet(animal.cat)

}

}

fun main(args: Array<String>){

val myPet = pet(animal.dog)

println(!myPet)

}

This produces pet(type=cat)

And this is the core thing, that while a Unary has a specific purpose normally you can totally use it the way that makes sense. This is really awesome and powerful but it doesn't stop there.

Normally when we think of something like the Unary not with a boolean, it goes from true to false (or vice versa), but it remains a boolean. There is nothing stating it has to be that way: