Scala的Infix Type与Self Types

Infix Type:中值类型,允许带有两个参数的类型

点击(此处)折叠或打开

  1. object Infix_Types {

  2.   def main(args: Array[String]) {
  3.     
  4.     object Log { def >>:(data:String):Log.type = { println(data); Log } }
  5.     "Hadoop" >>: "Spark" >>: Log //右结合,先打印出Spark,再打印出Hadoop
  6.     
  7.      val list = List()
  8.      val newList = "A" :: "B" :: list //中值表达式
  9.      println(newList)
  10.     
  11.     class Infix_Type[A,B] //中值类型是带有两个类型参数的类型
  12.     val infix: Int Infix_Type String = null //此时A是Int,B为String,具体类型名写在两个类型中间
  13.     val infix1: Infix_Type[Int, String] = null //和这种方式等价
  14.     
  15.     case class Cons(first:String,second:String) //中值类型
  16.     val case_class = Cons("one", "two")
  17.     case_class match { case "one" Cons "two" => println("Spark!!!") } //unapply
  18.     
  19.   }

  20. }
self-type

点击(此处)折叠或打开

  1. class Self {
  2.     self => //self是this别名
  3.     val tmp="Scala"
  4.     def foo = self.tmp + this.tmp
  5. }
  6. trait S1
  7. class S2 { this:S1 => } //限定:实例化S2时,必须混入S1类型
  8. class S3 extends S2 with S1
  9. class s4 {this:{def init():Unit} =>} //也能用于结构类型限定

  10. trait T { this:S1 => } //也能用于trait
  11. object S4 extends T with S1
  12. object Self_Types {

  13.   def main(args: Array[String]) {
  14.     class Outer { outer =>
  15.      val v1 = "Spark"
  16.      class Inner {
  17.      println(outer.v1)  //使用外部类的属性
  18.      }
  19.     }
  20.     val c = new S2 with S1 //实例化S2时必须混入S1类型
  21.   }

  22. }

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/28912557/viewspace-1983648/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/28912557/viewspace-1983648/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值