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

scala – 只有转换函数至少有两个参数时,才能将函数隐式转换为二

发布时间:2020-12-16 19:15:52 所属栏目:安全 来源:网络整理
导读:我有隐式转换和高阶函数的问题.似乎只有转换函数至少有两个参数,函数到二阶函数的隐式转换才有效. 作品: implicit def conv(foo: Integer = String): String = String = null 不起作用: implicit def conv(foo: Integer = String): String = String = Stri
我有隐式转换和高阶函数的问题.似乎只有转换函数至少有两个参数,函数到二阶函数的隐式转换才有效.

作品:

implicit def conv(foo: Integer => String): String => String = null

不起作用:

implicit def conv(foo: Integer => String): String => String => String = null

作品:

implicit def conv(foo: (Integer,Integer) => String): String => String => String = null

完整的失败点示例:

{
    implicit def conv(foo: Integer => String): String => String = null

    def baadf00d(foo: Integer): String = null

    def deadbeef(foo: String => String) = null

    deadbeef(conv(baadf00d))

    deadbeef(baadf00d)
}

{
    implicit def conv(foo: Integer => String): String => String => String = null

    def baadf00d(foo: Integer): String = null

    def deadbeef(foo: String => String => String) = null

    deadbeef(conv(baadf00d))

    deadbeef(baadf00d) // <-------- DOES NOT COMPILE!
}

{
    implicit def conv(foo: (Integer,Integer) => String): String => String => String = null

    def baadf00d(foo: Integer,bar: Integer): String = null

    def deadbeef(foo: String => String => String) = null

    deadbeef(conv(baadf00d))

    deadbeef(baadf00d)
}

我错过了什么?

谢谢!

解决方法

implicit def conv(foo: Integer => String): String => String => String = ???

  def baadf00d(i: Integer): String = ???
  def goodf00d: Integer => String = _ => ???

  def deadbeef(foo: String => String => String) = ???

  deadbeef(conv(baadf00d))

  deadbeef(baadf00d) // <-------- DOES NOT COMPILE!
  deadbeef(goodf00d) // <-------- COMPILE!
  // ˉ_(ツ)_/ˉ

问题是隐式转换如何对Scala起作用以及Scala中存在curried和uncurried函数的事实.

这应该是应该工作但不会,并且可能只是另一个编译器错误(随着您越来越多地使用Scala,准备好满足更多).

编辑:至于你的最后一个例子

implicit def conv(foo: (Integer,Integer) => String): String => String => String = null

def baadf00d(foo: Integer,bar: Integer): String = null

def deadbeef(foo: String => String => String) = null

那是因为函数定义确实匹配. conv期望函数(Int,Int)=> scala中的字符串和常规方法定义(uncurried),就像baadf00d的定义一样,变成了那个.

例如,一个函数:

def f(a: Int,b: Int): String

变成了一个

(Int,Int) => String

请注意,2个Int是有问题的!这与以下内容不同:

Int => Int => String

如果你要将baadf00d重新定义为:

def baadf00d: Integer => Integer => String = _ => _ => ???

该代码将无法编译,因为baadf00d现在“不同”,即使它正在做同样的事情.

有关更多信息,请查看对象的定义:

Function1,Function2,Function3 ....

http://www.scala-lang.org/api/current/#scala.Function2

(编辑:李大同)

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

    推荐文章
      热点阅读