casting l1 as ArrayList is working fine
# announcements
m
casting l1 as ArrayList is working fine
d
Why are you casting to
ArrayList
in the first place? It is not defined which list implementation is returned by these methods.
👆 1
m
yeah, basically I have a method that expects the output to be ArrayList
d
Then you will have to explicitly do
ArrayList(<existing list>)
, which creates another copy.
However if possible you should adjust those methods, code against interfaces (
List
,
MutableList
) whenever possible.
d
If you'll look at the response of
l2.distnct()
with your sample data then it is a String "A" and String cannot be casted directly to
ArrayList<String>
m
Yes, you're right. But why is returned type is different based on output, ideally it should be same irrespective of output, right?
I want to understand the reason behind this implementation in the language itself.
d
The stdlib optimizes small lists so that not the whole arraylist needs to be kept around for a small result
b
It's same, it's
List<T>
m
Copy code
However if possible you should adjust those methods, code against interfaces (`List`, `MutableList`) whenever possible.
why should I refactor to List and MutableList? @diesieben07
d
It's good OOP practice. You should not rely on a specific implementation, just specify which interface contract needs to be fulfilled
You see the reason right here: Your method demands an
ArrayList
, even though it really only needs a
MutableList
or even just a
List
. That limits your ability to use this method
d
you may try using
l2.distinct().toList()
d
You are required to convert everything to an
ArrayList
, even if its already a
List
@Dipali No. That returns a
List
, not
ArrayList
.
d
@diesieben07
l2.distinct()
can't be casted directly then
a.distinct().toList()
will be available for casting without any exception; despite this all I still wonder the return type of
distinct
is
List<T>
and should work directly.
d
The return type of
distinct
is
List
. That means it can return something other than
ArrayList
.
You can't just cast the result.
Same for
toList
.
t
toList()
does not guarantee the underline implementation is
Arraylist
. it might work today, but the contract is to just have a
List
, kotlin stdlib can change implementation any time and the cast would fail
👍 1
m
so what is the change I need to make?
it broke something in the production
b
ArrayList(.....distinct())
?
✔️ 1
🕺 1
1
m
Thank you folks 🙂