scala this.type

作者: Codlife | 来源:发表于2016-09-02 21:14 被阅读0次
     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类型的。
    spark 源码中大量使用了这种方式,比如spark mllib kmeans

      @Since("0.8.0")
      def setMaxIterations(maxIterations: Int): this.type = {
        require(maxIterations >= 0,
          s"Maximum of iterations must be nonnegative but got ${maxIterations}")
        this.maxIterations = maxIterations
        this
      }
    
      /**
       * The initialization algorithm. This can be either "random" or "k-means||".
       */
      @Since("1.4.0")
      def getInitializationMode: String = initializationMode
    
      /**
       * Set the initialization algorithm. This can be either "random" to choose random points as
       * initial cluster centers, or "k-means||" to use a parallel variant of k-means++
       * (Bahmani et al., Scalable K-Means++, VLDB 2012). Default: k-means||.
       */
      @Since("0.8.0")
      def setInitializationMode(initializationMode: String): this.type = {
        KMeans.validateInitMode(initializationMode)
        this.initializationMode = initializationMode
        this
      }
    
    

    相关文章

      网友评论

        本文标题:scala this.type

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