Home > OS >  How to initialize empty `util.Collection[String]` in scala?
How to initialize empty `util.Collection[String]` in scala?

Time:12-12

Can't unitialize it well, as

val topicAsCollection: util.Collection[String] = util.List[String]

isn't highlighted as an error, but compliation fails on

Error:(126, 59) class java.util.List is not a value
    val topicAsCollection: util.Collection[String] = util.List[String]

CodePudding user response:

The right way here is to initalize empty list the following way:

val topicAsCollection: util.Collection[String] = Collections.emptyList()

However, then it causes one more error:

This question already has answers here:

I have a code with Java collection in Scala

val topicAsCollection: util.List[String] = Collections.emptyList()
    topicAsCollection.add("recipes")

that fails in runtime

java.lang.UnsupportedOperationException was thrown.
java.lang.UnsupportedOperationException
    at java.base/java.util.AbstractList.add(AbstractList.java:153)
    at java.base/java.util.AbstractList.add(AbstractList.java:111)

So to initalize the java ArrayList collection in scala coirrectly, the correct initialization needs the explicit type and new:

val topicAsCollection: util.ArrayList[String] = new util.ArrayList[String]()
  • Related