如何在我的Kotlin类中创建一个匿名接口实现并使用它?

我怎么能有这样的Kotlin的Java代码? 甚至IDE也不会完全将其转换为Kotlin!

/** Defines callbacks for service binding, passed to bindService() */ private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; 

我尝试使用inner class但是我不能像这样使用它:

 @Override protected void onStart() { super.onStart(); // Bind to LocalService Intent intent = new Intent(this, LocalService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } 

你在这里创建一个匿名类。 在Kotlin中,这些是对象expression式 :

 val connection = object: ServiceConnection() { override fun onServiceConnected(className: ComponentName, service: IBinder) { ... } override fun onServiceDisconnected(arg0: ComponentName) { ... } }