我如何才能在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);
}
答案 0 :(得分:11)
你在这里创建一个匿名类。在Kotlin中,这些是object expressions:
val connection = object: ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
//Something to do
}
override fun onServiceDisconnected(arg0: ComponentName) {
//Something to do
}
}