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:
Question: is it possible to override local function 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?
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!
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.
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).
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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With