2
我可以找到一个指定关于coercion of functions passed to higher-order function(...的方法decorator.layout被自动强制为int类型的值的方法的Scala规则的文档=> String)。当调用更高阶的另一个函数时,可以调用Scala函数强制
如果我定义了以下内容。
object Foo {
def bar[T1, R](f: T1 => R): T1 => R = f
}
def fn1(s: String): Int = 1
然后在REPL我可以这样做:
scala> Foo.bar({ s: String => 1 })
res: String => Int = <function1>
scala> Foo.bar(fn1)
res: String => Int = <function1>
一切都很好,并清理到那里,但如果我更新Foo
:在REPL
object Foo {
def bar[T1, R](f: T1 => R): T1 => R = f
// NEW
def bar[T1, T2, R](f: Function2[T1, T2, R]): Tuple2[T1, T2] => R = { case (c1, c2) => f(c1, c2) }
}
然后:
scala> Foo.bar({ s: String => 1 })
res: String => Int = <function1>
scala> Foo.bar(fn1)
<console>:12: error: missing arguments for method fn1;
follow this method with `_' if you want to treat it as a partially applied function
Foo.bar(fn1)
这个叫一些bar(fn1)
需要按照以下方式更新与Foo
的第一个版本一起工作。
scala> Foo.bar(fn1 _)
res: String => Int = <function1>
这很好,但我想,以确保Scala编译器遵循哪些规则有关,当语法higherFn(fn)
可以使用,当它不能(和语法higherFn(fn _)
是必需的)。
我猜的高阶函数的多态性有事情做与...