美文网首页数客联盟
Scala中=>与<=的区别

Scala中=>与<=的区别

作者: Woople | 来源:发表于2016-10-06 16:32 被阅读0次

    <=含义

    小于等于号
    =>的使用


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

    scala> val triple = (x: Int) => 3 * x //定义了一个函数
    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
    
    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
    <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中。

    相关文章

      网友评论

        本文标题:Scala中=>与<=的区别

        本文链接:https://www.haomeiwen.com/subject/elbeyttx.html