将Java代码转换为Kotlin代码时出错

时间:2019-04-02 22:14:33

标签: java android kotlin

我在Java中有以下声明

private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {
        unregisterReceiver(mBroadcastReceiver);
    }
};

然后我尝试将其转换为Kotlin代码

private var mBroadcastReceiver:BroadcastReceiver = 
    object:BroadcastReceiver(){
        override fun onReceive(context: Context, intent: Intent) {
            unregisterReceiver(mBroadcastReceiver)
            stopSelf()
        }
    }

但是我有下一个错误

unregisterReceiver(mBroadcastReceiver)
  

变量mBroadcastReceiver必须初始化

1 个答案:

答案 0 :(得分:1)

尝试将this而不是mBroadcastReceiver传递给函数:

unregisterReceiver(this)