How can we create a `!` operator in Kotlin? For e...
# announcements
g
How can we create a 
!
 operator in Kotlin? For example, if I have MyClass defined as:
Copy code
MyClass() {
  run() {
    println("finished")
  }
}
I’d like to create a situation where doing something like this:
Copy code
val myObject = MyClass()
myObject!
is equivalent to
Copy code
myObject().run()
the methods will be more complex since this is for a special library that I’m doing, but the simple idea is like this. How can we define this operator? I think it is possible because we have the 
!!
  one.
d
#C0B9K7EP2
z
It’s not possible in the language right now. There is a very limited set of operators you can override, and even
!!
is not in that set.
g
I see, and which are the unary ones we can override? Is it only
+
,
-
and
!
? Which are their names?
z
g
I was checking this link, so it looks like we only have 5 available.
g
You can override the
not()
operator but you won’t be able to achieve the syntax you want, but rather:
Copy code
!myObject
g
Yes, you’re right, I’ve seen that. Well, maybe I’ll move forward with this one ^^ But it would be nice to create our own operators
🚫 8
z
I believe the current limitation was very intentional, since C++’s operator overloading flexibility has apparently caused a lot of pain.
☝️ 1
Even in kotlin, it’s a best practice to be very careful with overloading. When in doubt, better to write actual methods with names that are self-documenting.
g
I understand your point, but it is good to give us some liberty, because infix or type-safe builders are strange as well at a first glance. In my case, the way of writing, please see #C0B9K7EP2, would be very important for readability and using function names will not be so good, let’s say. The operator invoke, for example, does something strange, but in my case will be very helpful.
m
The freedom you advocate, caused a lot of pain 30 years ago with C++, pain and confusion that’s still going on today. I wrote C++ code when I was younger, and wouldn’t do it again not even for gold. I’m glad that Kotlin doesn’t let you define custom operators! If you want to use a particular syntax for a specific domain, consider creating and external DSL that compiles to or is interpreted by Kotlin. You can use ANTLR or even Jetbrains MPS to design it.
k
why not
myObject()
?
☝️ 1
g
In my case, myObject(), using the invoke operator, will do something else, which is very important for my case. I can use the ! (not) operator, but I’d rather prefer create something in the end, like the
!!
. This will do some complex computations that will go to an external routine and return, the motivation is to mimic a grammar language that I’m porting to Kotlin and write as less as possible to execute the code.