我只是将案例序列作为部分函数阅读,语法有点奇怪.
例如
def test: Int => Int = {
case 1 => 2
case 2 => 3
case _ => 0
}
Run Code Online (Sandbox Code Playgroud)
我希望它test没有参数,并返回一个类型的函数Int => Int
但经过一些测试后,它似乎需要一个int作为参数并返回一个int,所以我把它重写为......
def test1(i: Int): Int =
i match {
case 1 => 2
case 2 => 3
case _ => 0
}
Run Code Online (Sandbox Code Playgroud)
是test和test1平等?
前面的代码确实返回Int => Int类型的函数.
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) Client VM, Java 1.6.0_25).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :paste
// Entering paste mode (ctrl-D to finish)
def test: Int => Int = {
case 1 => 2
case 2 => 3
case _ => 0
}
// Exiting paste mode, now interpreting.
test: Int => Int
scala> test
res0: Int => Int = <function1>
scala> test.apply(1)
res1: Int = 2
Run Code Online (Sandbox Code Playgroud)
也许令人困惑的是,可以直接调用apply:
scala> test(1)
res2: Int = 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
187 次 |
| 最近记录: |