仅当要转换的函数具有至少两个参数时,才将函数隐式转换为二阶函数

use*_*643 7 scala implicit-conversion higher-order-functions

我有隐式转换和高阶函数的问题.似乎只有转换函数至少有两个参数,函数到二阶函数的隐式转换才有效.

作品:

implicit def conv(foo: Integer => String): String => String = null
Run Code Online (Sandbox Code Playgroud)

不起作用:

implicit def conv(foo: Integer => String): String => String => String = null
Run Code Online (Sandbox Code Playgroud)

作品:

implicit def conv(foo: (Integer, Integer) => String): String => String => String = null
Run Code Online (Sandbox Code Playgroud)

完整的失败点示例:

{
    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)
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

谢谢!

Ric*_*nry -1

implicit def conv1(a: Function1[Int, String]): Function2[String, String, String] = null
def baadf00d1(i: Int): String = null
def deadbeef1(arg: Function2[String, String, String]) = null  
deadbeef(baadf00d) // compiles
Run Code Online (Sandbox Code Playgroud)

A => B这是和之间的转换Function1[A,B]没有发生。

还有一个Function类型Predef- 请注意这里的类型差异:

scala> val f1: Function[Int, Int] = null
f1: Function[Int,Int] = null

scala> val f2: Function1[Int, Int] = null
f2: Int => Int = null

scala> :type f1
Function[Int,Int]

scala> :type f2
Int => Int
Run Code Online (Sandbox Code Playgroud)

它是 的别名Function1,但具有不同的类型界限(如下面的注释中指出的)。

  • 来自 Predef.scala “类型 Function[-A, +B] = Function1[A, B]” (2认同)