Created
February 3, 2014 02:27
-
-
Save mather/8778065 to your computer and use it in GitHub Desktop.
Scalaで単体とコレクションを透過的に扱う
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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