<=含義
小于等于號
=>的使用
使用=>
的場景比較多驱还,這里只羅列一些常見的使用方法
- By-Name參數(shù)
請參見《Scala的By-Name參數(shù)》 - 函數(shù)類型
在scala中函數(shù)和方法的概念是有一些區(qū)別的得运,如有興趣請參考《Scala中Method方法和Function函數(shù)的區(qū)別》粗蔚,這里只針對=>
做一些說明。
當(dāng)定義一個函數(shù)的時候众雷,需要使用=>
驹愚,例如
scala> val triple = (x: Int) => 3 * x //定義了一個函數(shù)
triple: Int => Int = <function1>
scala> def square(x: Int) = x * x //定義了一個方法
square: (x: Int)Int
scala> triple(3)
res1: Int = 9
scala> square(3)
res2: Int = 9
- 模式匹配
在Pattern Matching中會用到=>
两残,例如
object MatchTest extends App {
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "many"
}
println(matchTest(3))
}
- 自身類型(self type)
用《Scala for the Impatient》中的一段話來解釋自身類型
When a trait extends a class, there is a guarantee that the superclass is present in any class mixing in the trait. Scala has analternate mechanism for guaranteeing this: self types.
When a trait starts out with
this: Type =>
then it can only be mixed into a subclass of the given type.
可以看到當(dāng)使用這種語法的時候是需要=>
符號的,例如
scala> trait LoggedException {
| this: Exception =>
| def log(): Unit = {
| println("Please check errors.")
| }
| }
defined trait LoggedException
scala> import java.io.File
import java.io.File
scala> val file = new File("/user") with LoggedException
<console>:13: error: illegal inheritance;
self-type java.io.File with LoggedException does not conform to LoggedException's selftype LoggedException with Exception
val file = new File("/user") with LoggedException
在定義LoggedException使用了this: Exception =>
那么意味著LoggedException只能被“混入”Exception的子類中委刘,因為File不是Exception的子類丧没,所以報錯鹰椒。
scala> val re = new RuntimeException() with LoggedException
re: RuntimeException with LoggedException = $anon$1
因為RuntimeException是Exception的子類,所以LoggedException可以“混入”RuntimeException中呕童。