Only safe(?.)or non-null asserted(!!.) calls are a

2019-09-21 08:54发布

问题:

i am trying to add event for option menu items in android studio but i am getting this error message when i use item.itemId

only safe(?.)or non-null asserted(!!.) calls are allowed on a nullable receiver of type MenuItem

here is my code

override fun onOptionsItemSelected(item: MenuItem?): Boolean {

if(item.itemId==R.id.home){
    var homeIntent= Intent(this,SignIn::class.java)
    startActivity(homeIntent)

}
else if(item.itemId==R.id.sign_in){
    var signInIntent= Intent(this,SignIn::class.java)
    startActivity(signInIntent)

}
else if(item.itemId==R.id.close){
    System.exit(0)

}


return super.onOptionsItemSelected(item)
}

回答1:

The problem is item is defined as nullable . So you need to make sure that it should not be null before using it.

override fun onOptionsItemSelected(item: MenuItem?): Boolean {
    if(item?.itemId==R.id.home){
        var homeIntent= Intent(this,SignIn::class.java)
        startActivity(homeIntent)

    }
    else if(item?.itemId==R.id.sign_in){
        var signInIntent= Intent(this,SignIn::class.java)
        startActivity(signInIntent)

    }
    else if(item?.itemId==R.id.close){
        System.exit(0)

    }
    return super.onOptionsItemSelected(item)
}

Or you can use let

override fun onOptionsItemSelected(item: MenuItem?): Boolean {
    item?.let {
        if(it.itemId==R.id.home){
            var homeIntent= Intent(this,SignIn::class.java)
            startActivity(homeIntent)

        }
        else if(it.itemId==R.id.sign_in){
            var signInIntent= Intent(this,SignIn::class.java)
            startActivity(signInIntent)

        }
        else if(it?.itemId==R.id.close){
            System.exit(0)

        }
    }
    return super.onOptionsItemSelected(item)
}


回答2:

The easiest way to avoid this is in such cases, is to add elvis operator at first line

item ?: return false

But in this particular case, you can be sure, that item is not null by design, so you can safely remove question mark from method declaration

override fun onOptionsItemSelected(item: MenuItem): Boolean {