Function Scala隐式函数参数化

Function Scala隐式函数参数化,function,scala,implicit,parameterized,Function,Scala,Implicit,Parameterized,为什么这段代码不接受本地范围中定义的隐式函数? 这从哪里得到隐式函数 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: Str

为什么这段代码不接受本地范围中定义的隐式函数? 这从哪里得到隐式函数

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))
本地范围中的所有隐式def都没有被接受。 例如,impactestint给出结果5,我希望它通过将dble作为隐式返回10


它也不显示错误。implctest只返回传入的参数。

如果您将重写您的隐式表达式,则如下所示:

implicit val dble = (x: Int) => x + x
implicit val stringer = (x: String) => x + " no not a pity"
implicit val myclass = (x: Testimplcl) => new Testimplcl(x.a +1)
然后您将立即看到这种行为的原因。现在您遇到了隐式值不明确的问题:

scala: ambiguous implicit values:
  both method conforms in object Predef of type [A]=> <:<[A,A]
and value stringer in object ReflectionTest of type => String => String
match expected type String => String
println(implctest[String]("oh what a pity"))
                  ^

当您请求函数
a=>a
时,Scala提供了方法定义的隐式提升,例如

implicit def dble(x: Int):Int = x + x
也就是说,它将把它视为函数
dble
。因此,在隐式解析中,这不是一个立即可用的值

您遇到的问题是,对于任何类型,都有一个隐式的
A=>A
,定义为
Predef.confirms

 def conforms[A]: <:<[A, A]   // where <:< is a sub class of A => A
你可以看到冲突:

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]
                        ^
隐式[Int=>Int]//查找该类型的隐式转换
:49:错误:不明确的隐式值:
这两种方法都符合[A]=>Int类型的对象Predef
匹配预期类型Int=>Int
隐式[Int=>Int]
^


因此,简而言之,要求定制
a=>a
是不好的。如果您确实需要这样的东西,请使用自定义类型类,例如
Foo[a]extends(a=>a)

您是我的Doppelgänger吗?:)谢谢你的解释:)MyTransformer帮了大忙。谢谢:)我现在发现了问题。虽然def在localscope中,但它不是一个函数。它只有在用于函数时才成为函数对象。但不是隐式解析。是的,正如你所说,一旦我把它改为直接函数,我就得到了错误。
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]
                        ^