ycomp
ycomp

Reputation: 8563

How to fix my code to remove the casting warning?

I have some code similar to this:

private val elements: ArrayList<ISomeElement> = ArrayList()

...

override fun curElements(): Collection<GenericElement> {  
  ...
  return elements as Collection<GenericElement> // squigly underline here, unchecked cast warning

}

all ISomeElement objects in elements are GenericElement objects that implement ISomeElement

how could I fix my code to remove this warning? The code works fine, it's just the warning I'm asking about

I can't change the return type of the fun

Upvotes: 1

Views: 440

Answers (1)

mfulton26
mfulton26

Reputation: 31214

  1. If ISomeElement extends GenericElement then you will not get such a warning; you won't even need an explicit cast with the explicit function return type present.
  2. If ISomeElement does not extend GenericElement then there is no safe way to "cast" a Collection<ISomeElement> to a Collection<GenericElement>.

    You can map the elements to a new collection of the desired type:

    fun curElements(): Collection<GenericElement> {
        return elements.map { it as GenericElement }
    }
    

    You can also filter the collection if you know there may be some elements in the collection that do not implement GenericElement and you want to silently ignore them:

    fun curElements(): Collection<GenericElement> {
        return elements.filterIsInstance<GenericElement>()
    }
    

    If you are certain that all of the elements implement GenericElement then you can suppress the warning:

    fun curElements(): Collection<GenericElement> {
        @Suppress("UNCHECKED_CAST")
        return elements as Collection<GenericElement>
    }
    

    You can also change the type of elements to ArrayList<GenericElement> and then cast each ISomeElement instance to GenericElement as you add them to the collection:

    elements.add(iSomeElement as GenericElement)
    

Upvotes: 4

Related Questions