Implement java interface in Scala

I have the following code to create a cache using google collections:

val cache = new MapMaker().softValues().expiration(30, TimeUnit.DAYS).makeComputingMap( new com.google.common.base.Function[String,Int] { def apply(key:String):Int ={ 1 } }) 

And I get the following error message:

 error: type mismatch; found : java.lang.Object with com.google.common.base.Function[java.lang.String,Int]{ ... } required: com.google.common.base.Function[?, ?] new com.google.common.base.Function[String,Int] { ^ 

I am wondering why the types do not match?

Actual code:

 import com.google.common.collect.MapMaker trait DataCache[V] { private val cache = new MapMaker().softValues().makeComputingMap( new com.google.common.base.Function[String,V] { def apply(key:String):V = null.asInstanceOf[V] }) def get(key:String):V = cache.get(key) } 

Regards, Ali

PS - I use google collections v1

+6
scala
source share
2 answers

You need to specify type parameters for the final method call. You are looking at an interface like raw and scala cannot restore type information.

 val cache = new MapMaker().softValues().expiration(30, TimeUnit.DAYS).makeComputingMap[String, Int]( new com.google.common.base.Function[String,Int] { def apply(key:String):Int ={ 1 } }) 
+7
source share

Is the following being done?

 new com.google.common.base.Function[_,_] { 

If this does not work, you can save the declaration as it is now, and then add : com.google.common.base.Function[_, _] after it, for example:

 val cache = new MapMaker().softValues().expiration(30, TimeUnit.DAYS).makeComputingMap( new com.google.common.base.Function[String,Int] { def apply(key:String):Int ={ 1 } }: com.google.common.base.Function[_, _]) 

I heard that some of Google's stuff uses raw types that are pretty hard to integrate with Scala. And, in fact, you should drive back to hell, where they came from, but it's just IMHO.

Also, if you can compile this with -explaintypes , we can get a better idea of ​​what fails.

+1
source share

All Articles