gpt4 book ai didi

scala - 为什么我的隐式函数参数不起作用?

转载 作者:行者123 更新时间:2023-12-02 00:46:20 25 4
gpt4 key购买 nike

这是我的代码片段:

implicit def trick(s: String): String = s.toUpperCase    
def fun(s: String)(implicit f: String => String): String = f(s)
println(s"String is ${fun("abc")}")

当我运行它时,它打印“abc”而不是“ABC”。我在这里做错了什么?

附注

但是,如果我运行下一个代码

implicit val n: Int = 100
def add(n1: Int)(implicit n2: Int) = n1 + n2
add(7)

所有隐式魔法都可以正常工作。

最佳答案

通常这会起作用。编译器会通过 eta 扩展将隐式方法隐式转换为函数。比如说,如果我出于某种原因想要要求隐式 Int => List[Int]

implicit def trick(i: Int): List[Int] = List.fill(5)(i)

def fun(i: Int)(implicit f: Int => List[Int]): List[Int] = f(i)

scala> fun(4)
res5: List[Int] = List(4, 4, 4, 4, 4)

但你的问题是,另一个隐式String => String已经在来自Predef的范围内。即=:=[String, String],它扩展了String => String。因为它已经作为函数存在于作用域中,所以编译器认为不需要寻找其他任何东西。 并且,如果将隐式方法转换为隐式函数,您将得到一个不明确的隐式错误:

implicit val trick: String => String = _.toUpperCase

scala> fun("abc")
<console>:19: error: ambiguous implicit values:
both method $conforms in object Predef of type [A]=> <:<[A,A]
and value trick of type => String => String
match expected type String => String
fun("abc")

实际上,拥有隐式的String => String可能不是一个好主意。请改用包装函数的类型类。

case class Trick[A](f: A => A)

implicit val trick = Trick[String](_.toUpperCase)

def fun(s: String)(implicit t: Trick[String]): String = t.f(s)

scala> println(s"String is ${fun("abc")}")
String is ABC

关于scala - 为什么我的隐式函数参数不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32798618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com