Hello Kotliners. Is there a way to give an actual ...
# announcements
c
Hello Kotliners. Is there a way to give an actual name to callback functions so that I don’t have to implement a bunch of
invoke()
methods? For example:
Copy code
class Whatever(val callbackNumber1: (SomeParameter) -> Unit, val callbackNumber2: () -> Unit)
So now when call that instance in another object, I would have something like this:
Copy code
class AnotherObject : (SomeParameter) -> Unit , () -> Unit {
   private val whatever = Whatever(this, this)

   override fun invoke(){

   }

   override fun invoke(someParameter: SomeParameter){
    
   }
}
Or should I just stick to plain interfaces in this case?
n
type aliases?
z
Define fun interfaces?
c
@nanodeath
typealias
doesn’t solve the issue. @Zach Klippenstein (he/him) [MOD] Yup. That’s the way to go, I am just asking if there is some way to define actual names without creating an interface
e
you can say
(name: Type) -> Unit
but it's really just a hint, nothing more
n
oh, the problem isn't the names, it's the invokes? yeah, I think you need interfaces for that
e
yeah you want different interfaces
you can't implement both
(Foo) -> Unit
and
(Bar) -> Unit
at the same time due to erasure
c
It would probably be a good idea to have a feature like
@JVMName
for `typeAlias`es in the future, so that instead of having
invoke
name, we can define the name we want. It might probably be a little tricky for the compiler though.
Anyways, thanks all!
e
that can't work:
Copy code
class TwoFunctions : (Foo) -> Unit, (Bar) -> Unit { /* even assuming this works somehow */ }
val twoFunctions = TwoFunctions()
val fooFunction: (Foo) -> Unit = twoFunctions
val barFunction: (Bar) -> Unit = twoFunctions
fooFunction
and
barFunction
have the same
kotlin.jvm.functions.Function1
erasure, so their
fun invoke(T)
is the same
t
pair of '()->Unit' and '(String)->Unit' works.
e
yes, because that is
kotlin.jvm.functions.Function0
and
kotlin.jvm.functions.Function1
. but in general this is problematic