android-ktx icon indicating copy to clipboard operation
android-ktx copied to clipboard

Adding support for optional primitive values in Bundle

Open overengineered opened this issue 8 years ago • 3 comments

Sometimes an optional Int or Double value needs to be put into Bundle or read from it. The following API seems reasonable:

bundle.putNullableInt(VALUE, value);
val result = bundle.getNullableInt(VALUE);

Possible implementation:

fun Bundle.getNullableInt(key: String): Int?
        = if (containsKey(key)) getInt(key) else null

fun Bundle.putNullableInt(key: String, value: Int?)
        = value?.let { putInt(key, it) }

overengineered avatar Feb 07 '18 20:02 overengineered

I think we should avoid using nulls (especially in kotlin). Why not just use the default values? snipaste_2018-02-08_20-59-13

illuzor avatar Feb 08 '18 18:02 illuzor

Sometimes nulls have meaning. There's a reason Kotlin has type Int? in addition to Int. For example Activity may have selelectedItemId property and usually it's most appropriate to use Int? to be able to save the state when there is no selected item. And when writing state to Bundle these helpers would be useful. I agree that it is not high priority.

overengineered avatar Feb 09 '18 07:02 overengineered

One of the reasons to have nullable type is compatibility with java. Giving a meaning to null is what we intend to avoid. @illuzor gave a great point on this.

kioba avatar Feb 15 '18 09:02 kioba