Created
August 3, 2013 17:13
-
-
Save xuwei-k/6147157 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 trait Status | |
sealed trait HasID extends Status | |
sealed trait NoID extends Status | |
case class User[S <: Status]( | |
firstName: String, | |
lastName: String, | |
age: Int, | |
createdAt: java.util.Date, | |
private val _id: Int = 0 | |
){ | |
// copyメソッド呼ぶと、結局型安全じゃない(HasIDにもNoIDにも、どっちにもなってしまう)ので | |
// 結局copyするメソッド自作しないといけなくなる | |
def clone( | |
firstName: String = this.firstName, | |
lastName: String = this.lastName, | |
age: Int = this.age, | |
createdAt: java.util.Date = this.createdAt | |
): User[S] = User( | |
firstName, | |
lastName, | |
age, | |
createdAt | |
) | |
def id(implicit e: S =:= HasID): Int = _id | |
} | |
object User{ | |
def find(id: Int): Option[User[HasID]] = ??? | |
def create(user: User[NoID]): User[HasID] = ??? | |
def update(user: User[HasID]): User[HasID] = ??? | |
def delete(user: User[HasID]): Unit = ??? | |
} | |
object Main { //extends App{ | |
// メソッド作るの面倒だから、型引数直指定にした。ちょっと微妙 | |
val foo1 = User[NoID]("foo", "bar", 20, new java.util.Date) | |
// `foo1.id` はコンパイルエラー | |
val foo2 = User.create(foo1) | |
println(foo2.id) // create した後は、id呼べる | |
val foo3 = User.update(foo2.clone(age = 21)) | |
// 以下はコンパイルエラー | |
// User.create(foo2) | |
// User.create(foo2.clone(age = 21)) | |
User.delete(foo3) | |
// 以下はコンパイルエラー | |
// User.delete(foo1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
あざす!