简体   繁体   English

从Java迁移到kotlin-SAM包装程序的挑战吗?

[英]Migration from Java to kotlin - a SAM wrapper challenge?

I have a Java SAM interface and an implementation I want to translate in kotlin: 我有一个Java SAM接口和一个我想在kotlin中翻译的实现:

public interface CallbackWrapper {
    <T> Consumer<T> wrap(Consumer<T> consumer);
}

public class MainThreadWrapper implements CallbackWrapper {

    @Override
    public  <T> Consumer<T> wrap(Consumer<T> consumer) {
        return i -> {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(() -> consumer.accept(i));
        };
    }
}

Of course our project can deal with the java code but my neurons cannot. 当然,我们的项目可以处理Java代码,但我的神经元不能。 ;) ;)

Any help wiil be appreciated. 任何帮助将不胜感激。

Patrice 帕特里斯

The equivalent Kotlin class would look like this: 等效的Kotlin类如下所示:

class MainThreadWrapper : CallbackWrapper {
    override fun <T> wrap(consumer: Consumer<T>): Consumer<T> =
        Consumer { t ->
            val handler = Handler(Looper.mainLooper)
            handler.post { consumer.accept(t) }
        }
}

Note that the code uses SAM conversions two times, and they are only available for interfaces declared in Java. 请注意,该代码两次使用SAM转换 ,并且仅适用于用Java声明的接口。 The Kotlin alternatives are function types or object expressions for anonymous interface implementations. Kotlin的替代方法是用于匿名接口实现的函数类型对象表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM