Last active
August 29, 2015 14:11
-
-
Save dcaoyuan/f3aed1311a86f6739b14 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val p1: Function[(Int, Int), String] = { | |
x => "OK" | |
} | |
val p2: Function[(Int, Int), String] = { | |
x => | |
x match { | |
case (a: Int, b: Int) => "OK" | |
} | |
} | |
val p3: Function[(Int, Int), String] = { | |
case (a: Int, b: Int) => "OK" | |
} | |
先写以上三种 Function[(Int, Int), String] 的写法。 | |
注意,p1 是所有 Function[T, U] 的标准写法,尽管在这里 T 是 (Int, Int),但对于编译器来说, | |
最简单的处理方案就是统一按 p1 对待。 | |
然后看 p2,这个写法也是编译器很容易理解和处理的,没什么 magic。 | |
再然后,在 Scala 中,下列形式的代码: | |
{ | |
x => | |
x match { | |
case xxxxxx => | |
} | |
} | |
总是可以缩写为 | |
{ | |
case xxxxxx => | |
} | |
这样,就自然得到了 p3,这也是编译器的一个统一约定,编译器理解和实现也是很一致和简单的。 | |
其实在 Map[T, U] 的 foreach 和偏函数等处常看到这种缩写方式: | |
Map("a" -> 1, "b" -> 2).foreach { | |
entry => entry match { | |
case (k, v) => | |
} | |
} | |
总可以写成: | |
Map("a" -> 1, "b" -> 2).foreach { | |
case (k, v) => | |
} | |
对于 p1, p2, p3,按理应该只能这样调用: | |
p1((1, 2)) | |
但实际上 | |
p1(1, 2) | |
也行。这是编译器的 auto-detupling (adapted-args) 功能。如果你编译时 disable 掉,则只有 | |
p1((1, 2)) 编译可过,而 p1(1, 2) 编译不过: | |
scalac -Yno-adapted-args |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@advancedxy 谢谢,改过来了。