如何在Kotlin中调用接口?

时间:2019-06-12 08:19:56

标签: kotlin interface

我的工作中没有项目,他们要求我给我一个通行证,但是在通过整个项目后,此刻有一部分代码错误给了我。显然,这是我第一次来科特林,我不知道,但是我确实有一个想法。我试图解决它,但没有成功。所以我在寻求帮助。我在

的开头出现了错误
  

= SpeechService.Lintener {

代码在这里

private val mSpeechServiceListener = SpeechService.Listener { text: String?, isFinal: Boolean ->
    if (isFinal) {
        mVoiceRecorder!!.dismiss()
    }

    if (mText != null && !TextUtils.isEmpty(text)) {
        runOnUiThread {
            if (isFinal) {

                if (mText!!.text.toString().equals("hola", ignoreCase = true) || b == true) {
                    if (b == true) {
                        mText!!.text = null
                        mTextMod!!.text = text

                        repro().onPostExecute(text)
                        random = 2
                    } else {
                        b = true
                        mText!!.text = null
                        val saludo = "Bienvenido, ¿que desea?"
                        mTextMod!!.text = saludo
                        repro().onPostExecute(saludo)
                    }
                }

            } else {
                mText!!.text = text
            }
        }
    }
}

这里是界面

interface Listener {

    fun onSpeechRecognized(text: String?, isFinal: Boolean)

}

请帮帮我。错误是“接口侦听器没有构造函数”

1 个答案:

答案 0 :(得分:2)

仅当使用Java编写接口时,才可以使用SAM接口的SpeechService.Listener { }语法(请参见https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions)。因为该接口是用Kotlin编写的,所以您必须这样编写:

private val mSpeechServiceListener = object : SpeechService.Listener {

    override fun onSpeechRecognized(text: String?, isFinal: Boolean) {
        // Code here
    }

}

在Kotlin中,您实际上并不需要SpeechService.Listener接口。您可以只使用lambda函数。这取决于接口是来自库还是您自己编写的。

private val mSpeechServiceListener: (String?, Boolean) -> Unit = { text, isFinal ->
    // Code here
}
相关问题