Kotlin, how to assign callback implementation to a variable

user9257465 picture user9257465 · Mar 27, 2018 · Viewed 8.3k times · Source

I'm trying to assign a callback implementation of an interface (defined inside a class A) to a variabile defined inside another class B. Let's say that class A has the interface OnSomethingHappens which defines a doSomething method.

Inside class B I've defined my callback variable like this:

private lateinit var callback:A.OnSomethingHappens

I need to create an instance of class A passing callback variabile to the constructor in this way:

myinstanceA = A(callback)

I'm trying to assign an instance of an anonymous class that implements A.OnSomethingHappens using this code:

callback = object : A.OnSomethingHappens {
   override fun doSomething(..){
      //here I put the implementation of this method
   }
 }

but the compiler says "expecting member declaration" for my callback variable and "name expected" for object. What I'm doing wrong?

Instead, I'm able to define and at the same time assign the callback variable in this way:

private var callback = object : A.OnSomethingHappens {
      override fun doSomething(..){
        //here I put the implementation of this method
      }
    }

Why? Which are the differences and a possible solution?

Answer

Alexey Romanov picture Alexey Romanov · Mar 27, 2018

I'm trying to assign an instance of an anonymous class that implements A.OnSomethingHappens using this code: ...

This should work, but only inside a method:

class B {
    private lateinit var callback:A.OnSomethingHappens

    fun someMethod() {
        callback = object : A.OnSomethingHappens { ... }
    }
    ...
}

Given the error message and that private var compiles (which doesn't inside a method), you are trying to set it directly in the body of the class instead:

class B {
    private lateinit var callback:A.OnSomethingHappens

    callback = object : A.OnSomethingHappens { ... }
    ...
}

This is illegal: the only code you can write there is member definitions and init blocks.

Also, if you can initialize callback directly where it's defined or inside init, there's no point to lateinit in the first place.