HelloCW
HelloCW

Reputation: 2255

Why can't I get an error information when I convert a Long value to Int value in kotlin?

I use Code A to open a activity and pass a long value to parameter id.

I use Code B to get the value of parameter id, but I make a mistaken carelessness to using the code var myid =intent.extras.getInt("id"), and It should be var myid =intent.extras.getLong("id")

The system return an error value 0 for the parameter myid when I use var myid =intent.extras.getInt("id"), it cause me to debug the program again and again.

I think that the system should display an error information when I use var myid =intent.extras.getInt("id"), but the system give me an error value 0

Code A

startActivity<UIAddEditBackup>("id" to 2L)

Code B

class UIAddEditBackup: AppCompatActivity() { 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_add_edit_backup)      

        var myid =intent.extras.getInt("id")
        toast("This is my ID "+myid)
    }
}

Upvotes: 0

Views: 115

Answers (1)

Chandra Sekhar
Chandra Sekhar

Reputation: 19502

intent.extras.getInt("id") will return 0 as default value if it doesn't find any integer value with the same key.

If you want your own default value, then you can use intent.extras.getInt("id", yourDefValue)

There could be one more doubt asking why the long can't be casted into integer and return back. The simple answer for this is extras in Intent is nothing but an ArrayMap<String, Object>. So whenever we ask for an integer with getInt(key), it tries to do below operations:

1. Fetch the value using the given key.
2. Is the key exists?
3. No -> return 0 as default value
4. Yes -> Cast the value to `java.lang.Integer` and return the value
5. In case Casting fails, catch the ClassCastException and return default value (which is 0 in your case)

Upvotes: 1

Related Questions