码迷,mamicode.com
首页 > 其他好文 > 详细

第56讲:Scala中Self Types实战详解

时间:2015-09-15 14:21:18      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

今天学习了self type的内容,让我们来看下代码

package scala.learn

class Self{
  self =>
    val tmp = "Scala"
    def foo = self.tmp + this.tmp
}

trait S1
class S2 {this:S1 =>}
class S3 extends S2 with S1

trait T {this:S1 =>}

object S4 extends T with S1
object test94 {
  def main(args:Array[String]){
    class Outer { outer =>
      val v1 = "Spark"
      class Inner {
        println(outer.v1)
      }     
    }
    val c =new S2 with S1
   
   
  }
}


 首先,定义了一个类Self,在Self类里面,用self定义了this指针的别名(this就是该类的运行时实例),所以可以用self.tmp访问内部成员。

如在main方法中的Outer类,我们定义了该类的this指针的别名为outer,所以在内部类Inner里,我们可以使用outer.v1,即this.v1.

另一个用法是,比如,我们先定义一个特质S1,再定义一个类S2,但是S2中,我们通过this:S1的方式,定义S2必须混入S1的类型。

这样一来,S2就混入了S1.当有其他类继承自S2时,我们就必须这样定义了:class S3 extends S2 with S1.

 

 

分享下更多的scala资源吧:

 

百度云盘:http://pan.baidu.com/s/1gd7133t

 

微云云盘:http://share.weiyun.com/047efd6cc76d6c0cb21605cfaa88c416

 

360云盘: http://yunpan.cn/cQN9gvcKXe26M (提取码:13cd)

 

信息来源于 DT大数据梦工厂微信公众账号:DT_Spark

 

关注微信账号,获取更多关于scala学习内容

 

第56讲:Scala中Self Types实战详解

标签:

原文地址:http://www.cnblogs.com/qingyuesama/p/4809944.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!