使用Kotlin类中父类的函数

3phpmpom  于 2022-12-30  发布在  Kotlin
关注(0)|答案(1)|浏览(132)

我有下面的Java代码,它运行得非常好:

public class MainActivity extends AppCompatActivity {
    private final class EchoWebSocketListener extends WebSocketListener {
        @Override
        public void onMessage(WebSocket webSocket, String text) {
            output("Recieving: "+ text);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ....
    }
    private void output(final String txt) {
        //do something on UI
    }

}

在Kotlin尝试同样的事情是行不通的;我尝试了以下方法,但无法从EchoWebSocketListener访问该函数。以下是Kotlin中的代码:

class MainActivity : AppCompatActivity() {
    lateinit var start: Button
    lateinit var output: TextView
    var client = OkHttpClient()

    class EchoWebSocketListener : WebSocketListener() {
        override fun onOpen(websocket: WebSocket, response: Response) {
            websocket.send("Authentication - Samir")
            websocket.send("getScore")
        }
        override fun onMessage(Websocket: WebSocket, text: String) {
            output("Recieving: " + text)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    private fun output(text: String) {

    }
}

如何使函数输出可从EchoWebSocketListener中的覆盖方法访问?

vnjpjtjt

vnjpjtjt1#

感谢@Pawel;找到类上使用的内部关键字;参见文档。工作正常:

class MainActivity : AppCompatActivity() {
    lateinit var start: Button
    lateinit var output: TextView
    var client = OkHttpClient()

    inner class EchoWebSocketListener : WebSocketListener() {
        override fun onOpen(websocket: WebSocket, response: Response) {
            websocket.send("Authentication - Samir")
            websocket.send("getScore")
        }
        override fun onMessage(Websocket: WebSocket, text: String) {
            output("Recieving: " + text)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    fun output(text: String) {
        //do something
    }
}

相关问题