0

I have the following class

class Item {
    var name: String = ""

    constructor(n: String) {
        name = n
    }

}

On my main activity I have declared this:

var list: ArrayList<Object> = ArrayList<Object>()

When I try to do this

list.add(Item("Hey friend"))

The compiler complains about type mismatch (Object -> Item) which is obviously true but since Item is also an Object, shouldn't this be fine? I'm pretty sure you can do this in Java, whats the alternative?

I need the list to be of type object because I have to store different stuff in there, so changing it is not an option.

1 Answer 1

1

The supertype of all types in Kotlin is Any, not Object.

Other things you can improve in var list: ArrayList<Object> = ArrayList<Object>():

  • make it a val because immutability is preferred
  • If you need an explicit type declaration, use the interface List<Any
  • use Kotlin's collection builders listOf()
val items: List<Any> = listOf()`

Also, the class definition can be reduced to

class Item(val name: String) //could even be a data class
Sign up to request clarification or add additional context in comments.

2 Comments

One question regarding this, Any is not equivalent to Object right? So if I have a java class with a method that receives a list of type Object, would it work if I feed it a list of type Any?
It is being mapped to Object so yes, you should replace Java Object with Any (read here kotlinlang.org/docs/reference/java-interop.html#mapped-types)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.