GarouDan
06/10/2020, 11:23 PM! operator in Kotlin?
For example, if I have MyClass defined as:
MyClass() {
run() {
println("finished")
}
}
I’d like to create a situation where doing something like this:
val myObject = MyClass()
myObject!
is equivalent to
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.serebit
06/10/2020, 11:28 PMoperator fun invoke, but you can't create your own operators. This question also isn't applicable to Gradle ;)octylFractal
06/10/2020, 11:28 PM!! is a compiler/syntax feature, not a function definitionoctylFractal
06/10/2020, 11:29 PMGarouDan
06/10/2020, 11:30 PMGarouDan
06/10/2020, 11:30 PMGarouDan
06/10/2020, 11:30 PMnot operator, but I’d rather prefer to have it laterserebit
06/10/2020, 11:32 PMrun itself or an invoke operator functionoctylFractal
06/10/2020, 11:37 PM!! 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 methodGarouDan
06/10/2020, 11:42 PM