简体   繁体   中英

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 ?

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> 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM