Scala中=>與<=的區(qū)別

<=含義

小于等于號
=>的使用


使用=>的場景比較多,這里只羅列一些常見的使用方法

scala> val triple = (x: Int) => 3 * x //定義了一個(gè)函數(shù)
triple: Int => Int = <function1>

scala> def square(x: Int) = x * x //定義了一個(gè)方法
square: (x: Int)Int

scala> triple(3)
res1: Int = 9

scala> square(3)
res2: Int = 9
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)使用這種語法的時(shí)候是需要=>符號的,例如

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的子類中,因?yàn)镕ile不是Exception的子類,所以報(bào)錯(cuò)。

scala> val re = new RuntimeException() with LoggedException
re: RuntimeException with LoggedException = $anon$1

因?yàn)镽untimeException是Exception的子類,所以LoggedException可以“混入”RuntimeException中。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容