`

scala中的this.type

阅读更多

自从开始看scala的Parser相关的源码以来,我越来越觉得scala中很多处理方法就像是用黑魔法在与编译器打交道。不变成JVM上的c++誓不罢休?

 

看Programming in Scala 源码 33.6

abstract class Parser[+T] ... { p =>
...
  def ~ [U](q: => Parser[U]) = new Parser[T~U] {
  def apply(in: Input) = p(in) match {
    case Success(x, in1) =>
      q(in1) match {
         case Success(y, in2) => Success(new ~(x, y), in2)
         case failure => failure
      }
    case failure => failure
  }
}

 结果查2.9.1里的代码

def ~ [U](q: => Parser[U]): Parser[~[T, U]] = { lazy val p = q // lazy argument
      (for(a <- this; b <- p) yield new ~(a,b)).named("~")
    }

 named方法的定义

def named(n: String): this.type = {name=n; this}

 对这个地方一直不明白,查到了这篇文章 后才了解到它的作用。

  class A {def method1: A = this }
  class B extends A (def method2: B = this}
  val b = new B

如果调用b.method2.method1是可以的,但是如果想调用b.method1.method2就不行了。因为method1返回的是A类型的。

当然你可以在B中覆盖method1,以返回正确类型。但是scala中解决这个问题的办法就是this.type

class A { def method1: this.type = this }
class B extends A { def method2: this.type = this }
val b = new B

如果调用b.method1则编译器会知道method1返回的是B类型的。

 

自言自语:

    scala学习曲线过高,代码可读性差(也许我读得还不够多),大量的语法规则和复杂的类型申明让我头晕。是不是该继续尝试更为纯粹的clojure呢?

分享到:
评论

相关推荐

    Learning.Scala.Practical.Functional.Programming.for.the.JVM

    Author Jason Swartz demonstrates why Scala’s concise and expressive syntax make it an ideal language for Ruby or Python developers who want to improve their craft, while its type safety and ...

    Scala和设计模式.pdf

    接下来,我们将具体介绍几种在Scala中常见的设计模式,并探讨它们是如何在Scala中实现的。 ### 三、Singleton(单例模式) 单例模式是一种常用的模式,用于确保一个类只有一个实例,并提供一个全局访问点。在Java...

    Scala for the Impatient.pdf

    - **Varargs**: This feature allows a function to accept a variable number of arguments of the same type. For example: ```scala def sum(xs: Int*) = { var r = 0 for (x ) r += x r } ``` - **...

    Scala的Map相关方法整合

    `defretain(p:(A,B)=&gt;Boolean):Map.this.type` 保留满足条件的元素。 - **示例**:`val m = Map("a" -&gt; 1, "b" -&gt; 2, "c" -&gt; 3); m.retain{ case (k, v) =&gt; v &gt; 1 }` 结果为 `Map("b" -&gt; 2, "c" -&gt; 3)`。 #### 34....

    Scala and Spark for Big Data Analytics

    Learn Scala's sophisticated type system that combines Functional Programming and object-oriented concepts Work on a wide array of applications, from simple batch jobs to stream processing and machine ...

    Scala:Applied Machine Learning

    Scala for Data Science, the first module in this course, is a tutorial guide that provides tutorials on some of the most common Scala libraries for data science, allowing you to quickly get up to ...

    Scala语言规范中文教程

    - **方法与构造器**:Scala中的方法定义使用`= _`语法,构造器可以通过`def this(...)`来定义。 - **访问修饰符**:`private`, `protected`, `public`控制成员的可见性。 3. **函数式编程** - **函数是一等公民*...

    Learning-Scala-Practical-Functional-Programming-for-the-JVM.pdf

    generic-supporting type system. For these and any other developers who want to learn how to develop in the Scala programming language, this book provides an organized and examples-based guide that ...

    scala for the impatient

    specific languages * Understanding the Scala type system * Applying advanced 'power tools' such as annotations, implicits, and delimited continuations Scala is rapidly reaching a tipping point that ...

    Scala的HTTP服务接口http4s.zip

     // You can use helpers to send any type of data with an available Writable[T]  case GET -&gt; Root / "synchronous" =&gt; Ok("This is good to go right now.") } 标签:...

    lambda-scala:Scala 中的类型级 lambda 演算

    : B , B ]() // this checks type equality type S = x - &gt; : y - &gt; : z - &gt; : ( x @@ z @@ (y @@ z) ) type K = x - &gt; : y - &gt; : x type result = ( S @@ K @@ K @@ a ) # - &gt; * Equals [result, a] 在可以找到更...

    Object-Orientation, Abstraction, and Data Structures Using Scala, 2nd Edition

    The videos show construction of code from the ground up and this type of "live coding" is invaluable for learning to program, as it allows students into the mind of a more experienced programmer, ...

    lisc:Scala 中的列表解释

    This is a toy Lisp interpreter, written in Scala.Type :q to leave lisc&gt; ( defn fact [x] ( if ( &lt;= x 1 ) 1 ( * x ( fact ( - x 1 )))))==&gt; ()lisc&gt; ( fact 5 )==&gt; 120 输入:q退出 REPL。特殊表格目前有四个...

    Functional Programming Patterns in Scala and Clojure(Pragmatic,2013)

    Solve real-life programming ... By using both the statically typed, type-inferred Scala and the dynamically typed, modern Lisp Clojure, you'll gain a broad understanding of functional programming.

    GeoMesa Spark.docx

    val dataFile = this.getClass.getClassLoader.getResource("jts-example.csv").getPath val df = spark.read .schema(schema) .option("sep", "-") .option("timestampFormat", "yyyy/MM/dd HH:mm:ss ZZ") ....

    scala in depth

    In particular, this book covers Scala’s implicit and type systems in detail before discussing how these can be used to drastically simplify development. The book promotes the “blended style” of ...

    tinyplate:微型Scala模板引擎

    Templateval template : Template = Template ( " This is a {{subject.name}} {{subject.type}} " )// template: Any =&gt; String = tinyplate.Template$$$Lambda$1317/0x000000080184b840@40c28b0dval result = ...

    Programming Scala

    Scala quickly, and explains what makes this language ideal for today’s scalable, distributed, component-based applications that support concurrency and distribution. You’ll also learn how Scala ...

Global site tag (gtag.js) - Google Analytics