how can i add an item to an AbstractList? `kotlin...
# announcements
s
how can i add an item to an AbstractList?
kotlin.collections.EmptyList cannot be cast to Kpp_gradle$1$1$1$a
Copy code
fun <E> addOne(v: AbstractList<E>) {
    v.add(listOf<E>() as E)
}

class a {
    val empty : Int = 0
}

fun ret() {
    val f = arrayListOf<a>()
    f.add(a())
    println("type of f is ${f.javaClass}")
    println("type of f[0] is ${f[0].javaClass}")
    addOne(f)
    println("type of f is ${f.javaClass}")
    println("type of f[1] is ${f[1].javaClass}")
    abort()
}
s
That code doesn't do what you think it does
s
what does it do?
s
You're trying to cast a
List<E>
to the type
E
, which is pretty much guaranteed to fail. Then adding that to the passed
v
list
like if
E
is
Int
, you're trying to cast a list of integers to an integer
even if it did succeed, it wouldn't do anything, since the list you create is empty anyway
and for future reference,
listOf
will return a
List
, which cannot be modified.
mutableListOf
will return a
MutableList
, which can be modified
s
ok, so would it be possible to do this generically that work for any type of list
would this suffice?
Copy code
fun <E> addOne(v: AbstractList<E>) {
    v.add(v[0])
}
s
What are you trying to do?
s
create a function that resizes a list to the desired size
s
s
too low-level for me. What's the problem with the add-method in AbstractList again? https://docs.oracle.com/javase/8/docs/api/java/util/AbstractList.html#add(E) so if you want to add an element to an abstract list use l.add(..), if you want to add a list/collection to another list use l.addAll(..) but "listOf<E>() as E" will never work. A list of E is not an instance of E (not even if the list only contains one element, in this case it's empty which doesn't change anything). Maybe you come from Groovy and are used to type coercion?? I'm a bit at a loss here. The realloc-code you linked looks very advanced, but the mistake in the code you provided is quite basic, so it's hard to gauge on which level to answer your question.
s
thats ok, i got it working
s
@Stephan Schroeder The problem is that he’s set on doing it in a way that doesn’t make any sense. Instead of providing a default value via a function parameter or a basic parameter, he wants to have the function create a default value, and has elected to use a when expression that covers all the cases he expects (including default values for primitives, and creating instances via reflection based on the class of the first element). It’s completely asinine, but he refuses to listen to anyone telling him how asinine it is.