Scala中=>与<=的区别

<=含义

小于等于号
=>的使用


使用=>的场景比较多,这里只罗列一些常见的使用方法

  • By-Name参数
    请参见《Scala的By-Name参数》
  • 函数类型
    在scala中函数和方法的概念是有一些区别的,如有兴趣请参考《Scala中Method方法和Function函数的区别》,这里只针对=>做一些说明。
    当定义一个函数的时候,需要使用=>,例如
scala> val triple = (x: Int) => 3 * x //定义了一个函数
triple: Int => Int = 

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.

可以看到当使用这种语法的时候是需要=>符号的,例如

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
: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中。

你可能感兴趣的:(Scala中=>与<=的区别)