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
Nothingis the most restrictive of all (nothing can beNothing!), Scala choosesLinkedBlockingQueue[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:
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
initialis another Java collection that is typed as containing strings,would just work, as it would read off the
Stringtype frominitial.