wathek
03/25/2019, 5:37 PMas
and setting the type of a variable, for instance:
val ids: List<Int> = environment.getArgument('ids')
VS
val ids = environment.getArgument('ids') as List<Int>
Jordan Stewart
03/25/2019, 5:40 PMas
will let this happen (although your IDE may warn you) and then fail at runtime.streetsofboston
03/25/2019, 5:41 PMgetArgument
function does not accept generic type-parameters.
But if it does, and both of your statements compile, i think the 2nd one may not be optimized away by the compiler and would incur a slight performance hit due to the explicit cast.wathek
03/25/2019, 5:43 PMJordan Stewart
03/25/2019, 5:45 PMwathek
03/25/2019, 5:46 PMPavlo Liapota
03/25/2019, 6:37 PMgetArgument
function has only one generic type parameter, then I would prefer to write:
val ids = environment.getArgument<List<Int>>('ids')
But of course I am just guessing function signature.streetsofboston
03/25/2019, 6:39 PMval ids: List<Int> = ...
, if I wanted to write out the type of ids
as well.
This would keep the variable name ids
as close as possible to the variable type List<Int>
Jordan Stewart
03/25/2019, 6:43 PMPavlo Liapota
03/25/2019, 6:48 PMids
variable declaration for some reason, then you would need to change how you call the function.streetsofboston
03/25/2019, 6:53 PMgetArgument
function, that situation would rarely occur. You usually would wind up assigning the return value of the getArgument
function call to either a local variable (e.g. val ids
) or to a parameter of another function or a property, and parameters and properties have a type-definition,wathek
03/25/2019, 6:59 PMgetArgument
signature is as following <T> T getArgument(String name);
Pavlo Liapota
03/25/2019, 7:12 PMval list = listOf(1, "one", 3.14)
val ints = list.filterIsInstance<Int>()
I know the following code wouldn’t compile (maybe with new type inference it will 🙂 ), but would you write it like this?
val list = listOf(1, "one", 3.14)
val ints: List<Int> = list.filterIsInstance()
My point is that I like to treat this kind of generics as basically arguments to a function call.Jordan Stewart
03/25/2019, 7:23 PMstreetsofboston
03/25/2019, 7:24 PMfilterIsInstance<Int>()
.
However, I tend to write functions with a regular (non-reified) type parameter using your val ints: List<Int>
example instead.
(I must admit, this is probably because val ints: List<Int> = list.filterIsInstance()
does not compile because this function is defined as inline fun <reified R> Iterable<*>.filterIsInstance(): List<@kotlin.internal.NoInfer R>
). The NoInfer
kinda forces your hand 🙂 The new type inference is not needed; the NoInfo annotation prevents type-inference.Pavlo Liapota
03/25/2019, 7:47 PM