[英]Functions in scala
我很难理解以下内容在scala中的含义:
f: Int => Int
是功能吗? f: Int => Int
和def f(Int => Int)
什么区别?
谢谢
假设f: Int => Int
是val f: Int => Int
的错字,
和def f(Int => Int)
是def f(i: Int): Int
的错字。
val f: Int => Int
表示值f
为Function1[Int, Int]
。
首先, A => B
等于=>[A, B]
。
这只是一个快捷方式,例如:
trait Foo[A, B]
val foo: Int Foo String // = Foo[Int, String]
其次, =>[A, B]
等于Function1[A, B]
。
这称为“类型别名”,定义如下:
type ~>[A, B] = Foo[A, B]
val foo: Int ~> String // = Foo[Int, String]
def f(i: Int): Int
是一个方法,而不是一个函数。
但是值g
是Function1[Int, Int]
,其中val g = f _
被定义。
f: Int => Int
表示f
类型为Int => Int
。
这是什么意思? 这意味着f
是一个获取Int
并返回Int
的函数。
您可以使用
def f(i: Int): Int = i * 2
或搭配
def f: Int => Int = i => i * 2
甚至
def f: Int => Int = _ * 2
_
是用于指定自变量的占位符。 在这种情况下,参数的类型已经在Int => Int
定义了,因此编译器知道此_
的类型是什么。
以下再次等同于上述定义:
def f = (i:Int) => i * 2
在所有情况下, f
类型都是Int => Int
。
那么,这是什么箭头? 如果您在类型位置(即需要输入的位置)看到此箭头,则表示该功能。
例如在
val func: String => String
但是,如果您在匿名函数中看到此箭头,它将把参数与函数主体分开。 例如在
i => i * 2
为了稍微详细说明Nader的答案,f:Int => Int经常出现在高阶函数的参数列表中,因此
def myHighOrderFunction(f : Int => Int) : String = {
// ...
"Hi"
}
是一个愚蠢的高阶函数,但显示了如何说myOrderFunction将参数f用作参数,f是一个将int映射到int的函数。
因此,我可以合法地这样称呼它,例如:
myHighOrderFunction(_ * 2)
一个更说明性的示例来自Odersky的Programming Scala:
object FileMatcher {
private def filesHere = (new java.io.File(".")).listFiles
private def filesMatching(matcher: String => Boolean) =
for (file <- filesHere if matcher(file.getName))
yield file
def filesEnding(query: String) = filesMatching(_.endsWith(query))
def filesContaining(query: String) = filesMatching(_.contains(query))
def filesRegex(query: String) = filesMatching(_.matches(query))
}
在这里,filesMatching是一个高阶函数,我们定义了其他三个函数,这些函数将其传递给不同的匿名函数以进行不同类型的匹配。
希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.