ITPub博客

首页 > 应用开发 > Java > Scala的Infix Type与Self Types

Scala的Infix Type与Self Types

原创 Java 作者:541732025 时间:2016-01-28 17:21:25 0 删除 编辑
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博客 ” ,链接:https://blog.itpub.net/28912557/viewspace-1983648/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2013-05-23

  • 博文量
    127
  • 访问量
    515713