hihi, does anyone knows why this works? ``` fun &...
# announcements
a
hihi, does anyone knows why this works?
Copy code
fun <T> Intent.getSerializableOrDefault(name: String, default: T) =
      getSerializableExtra(name) as T ?: default
my guess is that being T a non-nullable type this should crash while trying to cast, right? But apparently in my test it works:
Copy code
@Test fun `should get default`() {
        val default = ASerializableClass(2)

        assertThat(Intent().getSerializableOrDefault("a", default)).isEqualTo(default)
    }
Slack Conversation
d
as T
is an unchecked cast, it does not actually do any check, it says "ok I'll assume this is a T now".
a
but if you do
null as String
it will crash
d
Yes, because
String
is a concrete type.
T
is a type parameter, it could be any type, it's erased.
T
could be
String?
, too.
a
but is not in that case
assertThat(Intent().getSerializableOrDefault<ASerializableClass>("a", default)).isEqualTo(default)
that still works
d
Yes, but while compiling
getSerializableOrDefault
the compiler does not know that.
At compile time it is not known what
T
is, so you cannot check for it.
a
Sorry still don't get it 😅 at the end T in my specific case is gonna be a non-nullable type because the default is not gonna be null, so either the compiler is doing some extra checks that i'm not aware of or that should crash, no?
d
Generics are erased. Once compiled your
getSerializableOrDefault
method looks like this:
Copy code
fun Intent.getSerializableOrDefault(name: String, default: Any?)
And
as T
does nothing at runtime. There is no actual type-check performed.
t
you can cast it to a
T?
so that it is more clear
a
ahhhh i see
d
It would still be unchecked, @trevjones
a
yep, i could use
as? T
or
as T?
, but Take is still right
cool thanks @diesieben07 !!
t
checked or not doesn’t matter as much I am more concerned about it being clear what the expectation is