Kotlin has not
operator and !
which both will reverse the value of the boolean, but I want to know what is the differences between them and when to use not
or !
?
They’re the same thing, and !
is basically always preferred. not()
is an operator fun
, which means it can be called with !
.
Kotlin operators are just a special syntax to call special functions.You can define them by adding a function to any class
operator fun MyClass.not() = TODO()
When you call !someValue
kotlin automatically translates this to someValue.not()
(if there is an operator function defined).
This is useful if you write your custom maths library, eg. for complex numbers but can be used in other situations as well. It’s aslso used to make using BigDecimal
easier.
Generally you should use the operator and not the function. So prefer !someValue
over someValue.not()
.
If you want to know more about operator overloading you can look here:
https://kotlinlang.org/docs/reference/operator-overloading.html
if the !
is preferred I don’t understand why not
got invented in the first place. could you give example of calling not
where it has the meaning of its invention in the first place?
Every overloadable operator in Kotlin must have a regular name associated with it. For instance, +
can be overloaded by defining operator fun plus
. Similarly, not
is the name chosen for !