Scala各种类型实战

结构类型

    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 S1
class S2 { this : S1 => }
class S3 extends S2 with S1

trait T { this : S1 => }
object S4 extends T with S1

object 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值