Scala的Infix Type与Self Types

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

object Infix_Types {

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

}

self-type

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

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

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

你可能感兴趣的:(Scala的Infix Type与Self Types)