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

斯卡拉隐含的提升

发布时间:2020-12-16 09:59:33 所属栏目:安全 来源:网络整理
导读:我想从A =隐式转换函数. B到列表[A] =列表[B]. 我写了以下隐含的定义: implicit def lift[A,B](f: A = B): List[A] = List[B] = ... 不幸的是,当我编写以下代码时,隐式不会被应用: val plusOne: (List[Int]) = List[Int] = (x: Int) = (x + 1) 如果我用显
我想从A =>隐式转换函数. B到列表[A] =>列表[B].

我写了以下隐含的定义:

implicit def lift[A,B](f: A => B): List[A] => List[B] = ...

不幸的是,当我编写以下代码时,隐式不会被应用:

val plusOne: (List[Int]) => List[Int] = (x: Int) => (x + 1)

如果我用显式时间注释函数,它工作正常.

为什么?我该如何解决?

UPDATE.似乎问题是匿名函数特有的.相比:

@Test
def localLiftingGenerics {
  implicit def anyPairToList[X,Y](x: (X,Y)): List[X] => List[Y] = throw new UnsupportedOperationException  

  val v: List[String] => List[Int] = ("abc",239)
}

@Test
def localLiftingFuns {
  implicit def fun2ListFun[X,Y](f: X => Y): List[X] => List[Y] = throw new UnsupportedOperationException

  val v: List[String] => List[Int] = ((x: String) => x.length)
}

第一个编译得很好.第二个标记为错误

解决方法

根据 The Scala Language Specification /表达式/匿名函数(6.23):

If the expected type of the anonymous function is of the form
scala.Functionn[S1,…,Sn,R],the expected type of e is R

因此,函数的结果类型将被推断为List [Int],除非您将函数定义与函数值赋值分开(以消除期望的类型):

val function = (x: Int) => (x + 1)
val plusOne: (List[Int]) => List[Int] = function

或明确指定函数类型:

val plusOne: (List[Int]) => List[Int] = ((x: Int) => (x + 1)): Int => Int

(编辑:李大同)

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

    推荐文章
      热点阅读