【问题标题】:How to instantiate an anonymous class that implements an interface in Kotlin如何在 Kotlin 中实例化实现接口的匿名类
【发布时间】:2023-03-08 23:24:01
【问题描述】:

在 Java 中,实例化接口对象就像 new Interface()... 一样简单,并在 AnimationListener 上覆盖所有必需的函数,如下所示

private void doingSomething(Context context) {
    Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
    animation.setAnimationListener(new Animation.AnimationListener() {
        // All the other override functions
    });
}

然而,当我们在 Kotlin 中键入时

private fun doingSomething(context: Context) {
    val animation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in)
    animation.setAnimationListener(Animation.AnimationListener(){
        // All the other override functions
    })
}

It error 投诉 unresolved References AnimationListener.

【问题讨论】:

标签: interface kotlin


【解决方案1】:

the documentation中所述:

animation.setAnimationListener(object : Animation.AnimationListener {
    // All the other override functions
})

【讨论】:

  • 谢谢!伟大的。当我在kotlinlang.org/docs/reference/interfaces.html 中搜索时,它甚至没有触及任何内容。文档非常模糊。在网上搜索也找不到。找到这个的唯一地方是手动编写 Java 代码,然后转换它......希望我的 stackoverflow 问题能帮助其他人快速搜索它以找到它。谢谢!
  • 我建议改进 kotlin slack 中的文档。我同意在文档中很难找到这些信息。
  • 听起来不错!
  • @Ultimo_m 对此感到抱歉。带括号的语法对于创建扩展类并调用其默认构造函数的匿名对象是正确的。在实现接口时,括号确实不应该在那里。
【解决方案2】:

鉴于接口没有空的构造函数,显然最新的方法(使用 Kotlin 1.0.5)现在没有括号。

animation.setAnimationListener(object : Animation.AnimationListener {
    // All the other override functions
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-06
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多