1

私はScala 2.10.2を使用しており、次のような特性を定義しようとしています

trait Foo {
  def bar(a:String): String
  def bar(a:String): Int
}

コンパイラ エラーが発生しますmethod a is defined twice。正しい構文は何ですか?

4

4 に答える 4

8

ちょっと押したり引いたりで

trait Foo {
  def bar(a:String): String
  def bar(a:String)(implicit di: DummyImplicit): Int
}

class F extends Foo {
  def bar(a: String): String = "Hello"
  def bar(a: String)(implicit di: DummyImplicit): Int = 1
}

object Demo extends App {
  val f = new F()
  val s: String = f.bar("x")
  val i: Int = f.bar("x")
  println(s)
  println(i)
}

DummyImplicita (「メソッドが2回定義されている」を回避するため)および明示的な入力(メソッドの1つを選択するため)を使用して、微調整できます。

于 2013-07-26T20:13:37.140 に答える
3

なぜそれが役立つのかはわかりませんが、これを行うことができます:

scala> object Foo {
     | trait BarImpl[T] { def apply(str: String): T }
     | implicit object barInt extends BarImpl[Int] { def apply(str: String) = 1 }
     | implicit object barBoolean extends BarImpl[Boolean] { def apply(str: String) = true }
     | def bar[T](str: String)(implicit impl: BarImpl[T]) = impl(str)
     | }
defined module Foo

scala> Foo.bar[Int]("asdf")
res8: Int = 1

scala> Foo.bar[Boolean]("asdf")
res9: Boolean = true
于 2013-07-27T06:04:12.920 に答える