How can we create a `!` operator in Kotlin? For example, if I have MyClass defined as: ```MyClass(...
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.
s
You could always use something like
operator fun invoke
, but you can't create your own operators. This question also isn't applicable to Gradle ;)
o
!!
is a compiler/syntax feature, not a function definition
you could define it in the compiler, but not as a library
g
Ops, sorry, I posted in the wrong channel ^^
But interesting, what do you mean by defining it in the compiler?
It looks like, the !myObject is possible because we have the
not
operator, but I’d rather prefer to have it later
s
Custom operators significantly harm readability, and as such are impossible with Kotlin without creating your own compiler plugin. You'd be better off using either the function
run
itself or an
invoke
operator function
o
!!
is implemented as part of the kotlin compiler, so you could fork the compiler and add
!
yourself. then you'd be able to create code incompatible with the rest of the world, but hey, open source lets you do what you want 😛 I highly recommend against it, and the syntax is IMO not very sensible -- why does
!
mean
.run()
?
!!
means
checkNotNull(expr)
, it does not really run any code, so making
!
do that seems... out of place. Just use
operator fun invoke
,
myObject()
is at least clear about what it's doing -- invoking a user-defined method
☝️ 3
g
Hum, I see, either way the invoke one seems interesting to me. Thanks for sharing 😉