Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implements a java SAM interface in Kotlin?

In Java it is possible to write code like this:

model.getObservableProduct().observe(this, new Observer<ProductEntity>() {
    @Override
    public void onChanged(@Nullable ProductEntity productEntity) {
        model.setProduct(productEntity);
    }
});

However trying to override local function in Kotlin results in: enter image description here


Question: is it possible to override local function in Kotlin?

like image 529
0leg Avatar asked Jun 15 '17 08:06

0leg


People also ask

What is a SAM Interface in Kotlin?

Such interfaces are ubiquitous in the Android world and are often referred to as SAM interfaces, where SAM is short for Single Abstract Method. In this short tutorial, you'll learn everything you need to know to aptly use Java's SAM interfaces in Kotlin code. 1. What Is a SAM Conversion?

How to declare a functional interface in Kotlin?

An interface with only one abstract method is called a functional interface, or a Single Abstract Method (SAM) interface. The functional interface can have several non-abstract members but only one abstract member. To declare a functional interface in Kotlin, use the fun modifier. Copied!

What is a single abstract method in Kotlin?

An interface with only one abstract method is called a functional interface, or a Single Abstract Method (SAM) interface. The functional interface can have several non-abstract members but only one abstract member. To declare a functional interface in Kotlin, use the fun modifier.

Is there a way to override a method in Java with Kotlin?

There is a way, but it requires the Java method parameter to be annotated as @Nullable. With no access to the Java code, it seems to be possible only with an intermediate Java interface, see the other answer. Actually, a Kotlin intermediate interface is enough (overriding only one function with Int? paramater type).


1 Answers

try using object expression instead.

//       the parentheses must be removed if Observer is an interface  ---V
model.getObservableProduct().observe(this, object:Observer<ProductEntity>(){
   override fun onChanged(productEntity:ProductEntity?) {
      model.setProduct(productEntity);
   }
});

IF the Observer is a java SAM interface (kotlin SAM interfaces aren't currently supported) then you can using lambda expression instead as further:

model.getObservableProduct().observe(this, Observer<ProductEntity>{
      model.setProduct(it);
});

OR using a lambda expression instead, for example:

// specify the lambda parameter type ---v
model.getObservableProduct().observe<ProductEntity>(this) {
      model.setProduct(it);
};
like image 76
holi-java Avatar answered Sep 21 '22 21:09

holi-java