Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a java interface in Scala

Tags:

scala

I have the following code for building 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 am getting 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 don't match ?

The actual code is:

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)
}

Kind regards, Ali

PS - I am using google-collections v1

like image 247
Ali Salehi Avatar asked Jan 29 '10 13:01

Ali Salehi


2 Answers

You need to supply type parameters to the final method call. You are going through the raw type interface and scala cannot reconstruct the 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
     }
   })
like image 159
psp Avatar answered Sep 30 '22 14:09

psp


Does the following works?

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

If that doesn't work, you may wish to keep the declaration as it is right now, and then add a : com.google.common.base.Function[_, _] after it, like this:

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 have heard that some Google stuff use raw types, which are rather hard to integrate well with Scala. And, in fact, should be banished back to hell, where they came from, but that's just imho.

Also, if you could compile that with -explaintypes, we may get a better notion of what is failing.

like image 23
Daniel C. Sobral Avatar answered Sep 30 '22 14:09

Daniel C. Sobral