user266003
user266003

Reputation:

Collection <?> in Scala

I just started learning Scala with presence of a small experience in Java. I wonder, what would be the Scala's data type for Java's one of Collection <?> args?

Upvotes: 0

Views: 145

Answers (2)

Vladimir Matveev
Vladimir Matveev

Reputation: 127781

First of all, Scala collections form separate library from Java collections. Of course, you can use Java collections from Scala, but this is usually done in code which interoperates with some Java API, and pure Scala code usually uses Scala collections.

As for your question, wildcards are denoted by underscore character in Scala, so yes, Java class java.util.Collection<?> will look like java.util.Collection[_] in Scala.

BTW, if you want type bounds, that is, something like Collection<? extends SomeClass>, then they are achieved with the following syntax:

Collection<? extends SomeClass>   ->   Collection[_ <: SomeClass]
Comparator<? super SomeClass>     ->   Comparator[_ >: SomeClass]

However, as I said, you better not use Java collections in pure Scala code because they are much less convenient than their Scala counterparts. Scala collections have more complex hierarchy, and there is no direct equivalent of Java Collection, though. You can read this excellent tutorial on Scala collections, especially this page, which shows hierarchy of Scala collections.

Upvotes: 4

Suresh Atta
Suresh Atta

Reputation: 121998

Collection <?> args

It's written Collection (pronounced "collection of unknown"), that is, a collection whose element type matches anything. It's called a wildcard type for obvious reasons.

Read more about wildcards here

For Scala Existential types and Usage of WildCards in Scala

Upvotes: 1

Related Questions