加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:05:55 所属栏目:安全 来源:网络整理
导读:这是我的代码片段: 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")}") 当我运行它时,它打
这是我的代码片段:

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”.我在这做错了什么?

PS

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

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

所有隐含的魔法都很好.

解决方法

通常这会起作用.编译器会通过eta-expansion隐式地将隐式方法转换为函数.比如说,如果我想要一个隐含的Int =>由于某种原因列出[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)

但是你的问题是还有另一个隐含的String =>字符串已经来自Predef.即=:= [String,String],它扩展了String =>串.因为这已作为函数存在于作用域中,所以编译器不需要查找任何其他内容.并且,如果将隐式方法转换为隐式函数,则会出现模糊的implicits错误:

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 =>字符串可能不是一个好主意.请改为使用包装函数的类型类.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读