6

Scala でサービスが与えられた場合:

class ScalaService {
  def process1(s: Option[String], i: Option[Int]) {
    println("1: " + s + ", " + i)
  }
}

これはJavaから使用されます:

public class Java {
    public static void main(String[] args) {
        ScalaService service = new ScalaService();

        // This works, but it's confusing
        {
            scala.Option<String> so = scala.Option.apply("Hello");
            scala.Option<Object> io = scala.Option.apply((Object) 10);
            service.process1(so, io);
        }

        // Would be OK, but not really nice
        {
            scala.Option<Object> so = scala.Option.apply((Object) "Hello");
            scala.Option<Object> io = scala.Option.apply((Object) 10);
            service.process1(so, io); // Does not compile
        }

        // The preferred way
        {
            scala.Option<String> so = scala.Option.apply("Hello");
            scala.Option<Integer> io = scala.Option.apply(10);
            service.process1(so, io); // Does not compile
        }

    }
}

プリミティブ型と非プリミティブ型を別の方法で扱うことは避けたいと思います。

そこで、別の方法を追加してこれを回避しようとしました。

def process2(s: Option[String], i: Option[java.lang.Integer]) {
  print("2: ")
  process1(s, i.map(v => v.toInt))
}

ただし、これにはメソッドに別の名前が必要です。これは呼び出し元の観点から混乱を招く可能性があるため、他に可能性はありますか?

私は Scala 2.10.1 と Java 1.6 を使用しています。

4

2 に答える 2

3

私がテストしようとしている解決策は、を使用することですDummyImplicit。そのため、Scala メソッドと Java メソッドの両方に同じメソッド名を付けることができます。

class ScalaService {
  // To be called from Scala
  def process(s: Option[String], i: Option[Int])(implicit d: DummyImplicit) {
    println("1: " + s + ", " + i)
  }

  // To be called from Java
  def process(s: Option[String], i: Option[java.lang.Integer]) {
    print("2: ")
    process(s, i.map(v => v.toInt))
  }

次のように Scala から使用します。

object ScalaService extends App {
  val s = new ScalaService()
  s.process(Some("Hello"), Some(123))
}

そしてJavaから:

public class Java {
    public static void main(String[] args) {
        ScalaService service = new ScalaService();

        {
            scala.Option<String> so = scala.Option.apply("Hello");
            scala.Option<Integer> io = scala.Option.apply(10);
            service.process(so, io);
        }
    }

}
于 2013-06-20T07:55:38.240 に答える
2

メソッド シグネチャも少し混乱しますが、パターン マッチングを使用してさまざまな型を処理できます。

class ScalaService {
  def process1(s: Option[String], i: Option[Any]) {
    i match {
      case Some(i2:Int) => processInternal(s, Some(i2))
      case Some(i2:java.lang.Integer) => processInternal(s, Some(i2.intValue))
      case _ => processInternal(s, None) // or throw exception if you prefer
    }

    def processInternal(s:Option[String], i:Option[Int]) { 
      println("1: " + s + ", " + i) 
    }
  }
}

java.lang.Integerまた、Java からの呼び出しについてはわかりませんが、からへの暗黙的な変換Intも機能する可能性がありますか?

于 2013-06-12T17:39:39.650 に答える