11

たとえば、次のことが暗黙的に適用される式を作成するにはどうすればよいですか。

implicit def intsToString(x: Int, y: Int) = "test"

val s: String = ... //?

ありがとう

4

2 に答える 2

18

1つの引数の陰関数は、値を期待される型に自動的に変換するために使用されます。これらは暗黙的ビューとして知られています。2つの引数があると、機能しないか、意味がありません。

暗黙のビューをTupleN:に適用できます。

implicit def intsToString( xy: (Int, Int)) = "test"
val s: String = (1, 2)

関数の最終パラメータリストを暗黙的としてマークすることもできます。

def intsToString(implicit x: Int, y: Int) = "test"
implicit val i = 0
val s: String = intsToString

または、これら2つの使用法を組み合わせますimplicit

implicit def intsToString(implicit x: Int, y: Int) = "test"
implicit val i = 0
val s: String = implicitly[String]

ただし、この場合はあまり役に立ちません。

アップデート

マーティンのコメントを詳しく説明すると、これは可能です。

implicit def foo(a: Int, b: Int) = 0
// ETA expansion results in:
// implicit val fooFunction: (Int, Int) => Int = (a, b) => foo(a, b)

implicitly[(Int, Int) => Int]
于 2010-03-10T12:49:26.693 に答える
4

ジェイソンの答えは、1つの非常に重要なケースを見逃しています。最初の引数を除くすべてが暗黙的である複数の引数を持つ暗黙の関数...これには2つのパラメーターリストが必要ですが、質問の表現方法を考えると、範囲外ではないようです。

これは、2つの引数を取る暗黙の変換の例です。

case class Foo(s : String)
case class Bar(i : Int)

implicit val defaultBar = Bar(23)

implicit def fooIsInt(f : Foo)(implicit b : Bar) = f.s.length+b.i

サンプルREPLセッション、

scala> case class Foo(s : String)
defined class Foo

scala> case class Bar(i : Int)
defined class Bar

scala> implicit val defaultBar = Bar(23)
defaultBar: Bar = Bar(23)

scala> implicit def fooIsInt(f : Foo)(implicit b : Bar) = f.s.length+b.i
fooIsInt: (f: Foo)(implicit b: Bar)Int

scala> val i : Int = Foo("wibble")
i: Int = 29
于 2011-05-15T15:35:26.133 に答える