Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.concurrent.LinkedBlockingQueue put method requires Nothing as argument in Scala

Tags:

java

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

like image 905
user413633 Avatar asked Aug 07 '10 04:08

user413633


3 Answers

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.

like image 104
Rex Kerr Avatar answered Nov 15 '22 07:11

Rex Kerr


For concurrent collection you can use the google collections (Guava) wich has a GenericMapMaker factory.

Scala examples here and here

like image 22
oluies Avatar answered Nov 15 '22 06:11

oluies


I guessed right. The type must be specified as shown -

val queue=new LinkedBlockingQueue[String]
like image 27
user413633 Avatar answered Nov 15 '22 07:11

user413633