java.util.concurrent.LinkedBlockingQueue put method requires Nothing as argument in Scala
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 mism开发者_高级运维atch;
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]
Java raw types are a concession to backward compatibility and their usage considered bad style. In Scala you don't have raw types, so you must either specify them or the type inferencer must be able to infer them. Note that you can specify the parametric type on the left side, too:
val queue:LinkedBlockingQueue[String] = new LinkedBlockingQueue()
That makes here not much sense, but is important if you want to have a different type (e.g. Queue[String]
for your variable.
精彩评论