Scala各种类型实战

来源:互联网 发布:布比网络 编辑:程序博客网 时间:2024/06/05 15:15

  • 结构类型
  • Infix type
  • Self_Type
  • Dependency Injection
  • Abstract Types

结构类型

    def init1( res : { def open() : Unit} ) {      res.open    }    init1(new { def open() = println("Opened")})    type X = {def open() : Unit}    init1(new { def open() = println("Opened again")})    object A { def open() { println("A single object Opened")}}    init1(A)    class Structural { def open() = print("A class instance Opened")}    val structural = new Structural    init1(structural)

Infix type

    object Log {def >>: (data : String) : Log.type = { println(data); Log}}    "Hadoop" >>: "Spark" >>: Log    val list = List()    val newList = "A" :: "B" :: list    println(newList)    class Infix_type[A, B]    val infix : Int Infix_type String = null    case class Cons(first : String, second : String)    val case_class = Cons("one", "two")    case_class match { case "one" Cons "two" => println("Spark!!!")}

Self_Type

class Self{  self =>    val tmp = "Scala"    def foo =self.tmp +this.tmp}trait S1class S2 { this : S1 => }class S3 extends S2 with S1trait T { this : S1 => }object S4 extends T with S1object Self_Type {  val c = new S2 with S1}

Dependency Injection

trait Logger { def log (msg : String)}trait Auth {  auth : Logger =>  def act(msg : String){    log(msg)  }  }object DI extends Auth with Logger{  override def log(msg : String) = println(msg);}object Dependency_Injection {  def main(args: Array[String]): Unit = {    DI.act("Good luck")  }}

Abstract Types

trait Reader{  type In <: java.io.Serializable  type Contents  def read(in : In) : Contents}class FileReader extends Reader {  type In = String  type Contents = BufferedSource  override def read (name : In) = Source.fromFile(name)}object Abstract_Types {  def main(args: Array[String]): Unit = {    val fileReader = new FileReader    val content = fileReader.read("E:\\Hello.txt")    for(line <- content.getLines())      println(line)  }}
0 0