Skip to content

Instantly share code, notes, and snippets.

@mather
Created February 3, 2014 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mather/8778065 to your computer and use it in GitHub Desktop.
Save mather/8778065 to your computer and use it in GitHub Desktop.
Scalaで単体とコレクションを透過的に扱う
sealed abstract class MailList {
// コレクションとして扱うための抽象メソッド
def +(mailbox: Mailbox): MailList
// 別の型に変換するなどの処理
def publish: String = this match {
case Mailbox(str) => str
case MailboxList(list) => list.map(_.publish).mkString(",")
}
}
// 単体のクラス
case class Mailbox(str: String) extends MailList {
def +(mailbox: Mailbox) = MailboxList(Set(this) + mailbox)
}
// コレクション型のクラス
case class MailboxList(list: Set[Mailbox]) extends MailList {
def +(mailbox: Mailbox) = MailboxList(list + mailbox)
}
val a: MailList = Mailbox("hoge")
a.publish //=> hoge
val b: MailList = a + Mailbox("fuga")
b.publish //=> hoge,fuga
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment