1

このコードがローカル スコープで定義された暗黙的な関数を使用しないのはなぜですか? これは他のどこから暗黙の関数を取得しますか?

def implctest[T](a: T)(implicit b:T=>T):T = {b apply a}
class Testimplcl(val a:Int){
    override def toString() = "value of the 'a' is = "+a
}
implicit def dble(x: Int):Int = {x + x}
implicit def stringer(x: String):String = {x+" no not a pity"}
implicit def myclass(x: Testimplcl):Testimplcl = new Testimplcl(x.a +1)

implctest[String]("oh what a pity")
implctest[Int](5)
implctest[Testimplcl](new Testimplcl(4))

ローカル スコープの暗黙的な定義はどれも取り込まれません。たとえば、implctestInt が結果 5 を返す場合、dble を暗黙的として取得することで 10 が返されることを期待しています。

エラーも表示されません。implctest は、渡された引数を返すだけです。

4

2 に答える 2

2

function を要求するとA => A、Scala は次のようなメソッド定義からの暗黙的なリフトを提供します。

implicit def dble(x: Int):Int = x + x

つまり、それを関数として扱いますdble _。したがって、暗黙的な解決では、これはすぐに利用できる値ではありません。

あなたが抱えている問題は次のように定義された任意のタイプの暗黙的A => Aなものがあることです:Predef.conforms

 def conforms[A]: <:<[A, A]   // where <:< is a sub class of A => A

A => Bからのビューが必要なA場合はいつでもB、そのような「変換」が自動的に利用できるため、これは便利で必要です。

参照してください。直接関数を使用します。

implicit val dble = (x: Int) => x + x

競合が表示されます。

implicitly[Int => Int]   // look for an implicit conversion of that type

<console>:49: error: ambiguous implicit values:
 both method conforms in object Predef of type [A]=> <:<[A,A]
 and value dble of type => Int => Int
 match expected type Int => Int
              implicitly[Int => Int]
                        ^

というわけで、要するに、カスタムをお願いするのは良くないということA => Aです。そのようなものが本当に必要な場合は、 などのカスタム型クラスを使用してFoo[A] extends (A => A)ください。

于 2013-06-09T18:33:02.433 に答える