简体   繁体   中英

Scala - Java interop - is it possible to “choose” the called java method from scala?

I'm having some interop issues calling Jedis (Java) from my Scala code (scala 2.10.4).

I have a trait which I've implemented in an implicit class

I get the following error when calling a method on the underlying class

implicit class Redis(private val underlying: Jedis) extends com.dy.storage.Redis {
    override def del(keys: String*): Long = {
      underlying.del(keys: _*)
    }

    override def del2(keys: Seq[Array[Byte]]): Long = {
      underlying.del(keys: _*)
    }
}

Getting the following error ( scala 2.10.4 ):

no `: _*' annotation allowed here
[error] (such annotations are only allowed in arguments to *-parameters)
[error]       underlying.del(keys: _*)
[error]                          ^
[error] /Users/avnerbarr/workspace/redis-hashed-no `: _*' annotation allowed here
[error] (such annotations are only allowed in arguments to *-parameters)
[error]       underlying.del(keys: _*)
[error]                          ^

I tried to add a wrapper and move the problematic call outside of the implicit class:

    override def del(keys: String*): Long = {
      Wrapper.delete(underlying, keys)
    }


object Wrapper {
  def delete(u : Jedis, str: Seq[String]): Long = {
    u.del(str:_*)
  }
}

And then this error appears instead:

overloaded method value del with alternatives:
[error]   (x$1: String)Long <and>
[error]   (x$1: <repeated...>[String])Long <and>
[error]   (x$1: Array[Byte])Long <and>
[error]   (x$1: <repeated...>[Array[Byte]])Long
[error]  cannot be applied to (Char)
[error]     u.del(a:_*)
[error]       ^
[info] Checking every *.class/*.jar file's SHA-1.
[error] one error found

This code build with no problems at all when using scala 2.11 and only get the problem in scala 2.10

Would it be possible to "choose" and not leave to inference the correct method that should be called?

You should provide code of Jedis and com.dy.storage.Redis .

The following code compiles:

src/main/java/Jedis.java

interface Jedis {
  long del(String... keys);
  long del(byte[]... keys);
}

src/main/scala/com/dy/storage/Redis.scala

package com.dy.storage

trait Redis {
  def del(keys: String*): Long
  def del2(keys: Seq[Array[Byte]]): Long
}

src/main/scala/App.scala

object App {
  implicit class Redis(private val underlying: Jedis) extends com.dy.storage.Redis {
    override def del(keys: String*): Long = {
      underlying.del(keys: _*)
    }

    override def del2(keys: Seq[Array[Byte]]): Long = {
      underlying.del(keys: _*)
    }
  }
}

build.sbt

name := "scala2104"
version := "0.1"
scalaVersion := "2.10.4"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM