https://kotlinlang.org logo
Title
d

diesieben07

08/04/2017, 12:48 PM
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

aballano

08/04/2017, 12:48 PM
but if you do
null as String
it will crash
d

diesieben07

08/04/2017, 12:49 PM
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

aballano

08/04/2017, 12:50 PM
but is not in that case
assertThat(Intent().getSerializableOrDefault<ASerializableClass>("a", default)).isEqualTo(default)
that still works
d

diesieben07

08/04/2017, 12:50 PM
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

aballano

08/04/2017, 12:54 PM
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

diesieben07

08/04/2017, 12:55 PM
Generics are erased. Once compiled your
getSerializableOrDefault
method looks like this:
fun Intent.getSerializableOrDefault(name: String, default: Any?)
And
as T
does nothing at runtime. There is no actual type-check performed.
t

trevjones

08/04/2017, 12:55 PM
you can cast it to a
T?
so that it is more clear
a

aballano

08/04/2017, 12:55 PM
ahhhh i see
d

diesieben07

08/04/2017, 12:56 PM
It would still be unchecked, @trevjones
a

aballano

08/04/2017, 12:56 PM
yep, i could use
as? T
or
as T?
, but Take is still right
cool thanks @diesieben07 !!
t

trevjones

08/04/2017, 1:05 PM
checked or not doesn’t matter as much I am more concerned about it being clear what the expectation is