自身类型(self type)
来源:互联网 发布:ai矢量制图软件 编辑:程序博客网 时间:2024/04/29 04:17
看scala的源码的话很发现很多源码开头都有一句:self => 这句相当于给this起了一个别名为self
class Self { self => //代表this指针 ,也就是说 self 就 this的别名 val tmp = "scala" def foo = self.tmp + this.tmp}
self不是关键字,可以用除了this外的任何名字命名(除关键字)。就上面的代码,在Self 内部,可以用this指代当前对象,也可以用self指代,两者是等价的。
self type 两种使用场景
一、 用在有内部类的情况
如:
class Outer { out => val v1= "spark" class Inner { println(out.v1) // 用outer表示外部类,相当于Outer.this v1 } }
二、 对子类(或者对象)的约束
trait S1/** * this 不能称当别名,这里this:S1 是一个整体,就是说实例化S2时,要求S1必须混入 */class S2 {this:S1 =>} // 混入trait S1,强制要求 S2的实现类 去实现 S1class S3 extends S2 with S1trait T {this:S1 => }object S4 extends T with S1
this:S1 => 要求S2在实例化时或定义S2的子类时,必须混入指定的S1 类型,这个X类型也可以指定为当前类型
自身类型的存在相当于让当前类变得“抽象”了,它假设当前对象(this)也符合指定的类型,因为自身类型 this:S1 =>的存在,当前类构造实例时需要同时满足S1类型
写的不对的地方,烦请指点
0 0
- 自身类型(self type)
- scala进阶14-自身类型self type
- 【Scala类型系统】自身类型(self type)引用
- Scala之自身类型(Self Type)与蛋糕模式(Cake Pattern)
- 特质->self type:this
- LeetCode OJ 之 Product of Array Except Self (除了自身的数组的乘积)
- Newtonsoft.Json转换强类型DataTable错误:Self referencing loop detected with type ......
- 图像自身属性类型
- 类型编码(Type Encodings)
- Mat 的类型(type)
- 类型信息(Type Info)
- Type “”类型“”
- iOS 获取self类型
- swift - 类型中的self
- Scala类型 9:自身类型 & this别名
- 类型修饰符(type specifier)
- Struts2 result 返回类型(type)小结
- C++类型转换(Type Casting)
- VC++ 创建及调用Dll
- webservices(WS)
- codevs1028
- 1—N 一一对应 且不重复
- C#版七层登陆
- 自身类型(self type)
- 求简单多边形面积时非常有用的“鞋带公式”
- 关于本类类名的获取
- 搜狗输入法的分词算法
- Python internals: Symbol tables, part 2
- 浏览器调试动态js脚本
- JS刷新验证码
- android 自定义view 状态保存
- 匿名内存