2

So on Java I like to implement an interface directly on a local variable like this for example.

private SensorEventListener sensorEventListener = new SensorEventListener() {
    @Override
    public void onSensorChanged(SensorEvent event) {
        //implement here
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        //implement here
    }
};

So that later I can add that listener directly and be able to remove the listener afterwards.

I'm trying to achieve the same idea on Kotlin, to have a var that implement the interface, without having to define a new class that extents that.

Is it possible? What is the semantic?

Caio Faustino
  • 165
  • 1
  • 15

1 Answers1

8

You create an object the implements the interface, for your code,

var sensorEventListener = object : SensorEventListener {
    override fun onSensorChanged(event : SensorEvent) {

    }

    override fun onAccuracyChanged(sensor : Sensor, accuracy : Int) {

    }

}
iagreen
  • 31,470
  • 8
  • 76
  • 90
  • Thanks, through your answer I was able to find the session in the documentation that explains this. https://kotlinlang.org/docs/reference/object-declarations.html – Caio Faustino Apr 22 '18 at 01:38