Here is a snippet of the code-
import java.util.concurrent.LinkedBlockingQueue
def main(args:Array[String]) {
val queue=new LinkedBlockingQueue
queue.put("foo")
}
This gives me -
error: type mismatch;
found : java.lang.String("foo")
required: Nothing
queue.add("foo")
My understanding is its because of me not specifying the type of the elements going into the queue. If thats the case, how do we specify types in scala for the LinkedBlockingQueue instead of the default generic ones?
When you don't supply a type signature but one is needed, Scala uses the most restrictive signature possible. Since Nothing
is the most restrictive of all (nothing can be Nothing
!), Scala chooses LinkedBlockingQueue[Nothing]
.
But in this case, the restrictiveness means that you can't actually put anything into this highly-restrictive queue.
As you've already discovered, the solution is to specify the type of classes in the collection:
val queue = new LinkedBlockingQueue[String]
But note that the type inferencer can figure out the right type in other cases by following the "as restrictive as possible" rule. For example if initial
is another Java collection that is typed as containing strings,
val queue = new LinkedBlockingQueue(initial)
would just work, as it would read off the String
type from initial
.
For concurrent collection you can use the google collections (Guava) wich has a GenericMapMaker factory.
Scala examples here and here
I guessed right. The type must be specified as shown -
val queue=new LinkedBlockingQueue[String]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With