by shigemk2

当面は技術的なことしか書かない

構造的部分型

通常、関数に引数を渡す場合は、引数に指定された型かそのサブクラスである必要がある。

が、継承関係がなくても特定のシグネチャを持つメソッドを持っていれば、 引数に指定した型の派生型を渡すことが可能である。

class FileIO {
  def open(src:String):Boolean = { println(src + " file open"); true }
  def close:Unit = println("file close")
}

class DatabaseIO {
  def open(url:String):Boolean = { println(url + " connection open"); true }
  def close:Unit = println("connection close")
}

object IO {
  type IO = {
    def open(src:String):Boolean
    def close:Unit
  }

  def func(io:IO,src:String) = {
    io.open(src)
    println("func execute")
    io.close
  }

  def main(args: Array[String]) {
    func(new FileIO, "text.txt")
    func(new DatabaseIO, "databaseURL")
  }
}
$ scalac io.scala && scala IO
text.txt file open
func execute
file close
databaseURL connection open
func execute
connection close