您可以使用lazy val
:
scala> :paste
// Entering paste mode (ctrl-D to finish)
case class Person (val name: String, val surname: String)
case class Family (val nameFamily: String, val members: Set[Person])
lazy val f1 = new Family ("Red", Set(p1, p2))
lazy val p1 = new Person ("John", "Smith")
lazy val p2 = new Person ("Luis", "Smith")
// Exiting paste mode, now interpreting.
defined class Person
defined class Family
f1: Family = <lazy>
p1: Person = <lazy>
p2: Person = <lazy>
scala> f1
res0: Family = Family(Red,Set(Person(John,Smith), Person(Luis,Smith)))
如果您只想在创建对象后在某处设置一些值,则应使用 scala 2.10 中的 Promise:
import concurrent.{Promise, Future}
case class Person (val name: String, val surname: String)
class Family (val nameFamily: String) {
private val membersPromice = Promise[Set[Person]]
def setMembers(m: Set[Person]) { membersPromice.success(m) }
val membersFuture = membersPromice.future
def members = membersFuture.value.map(_.get)
override def toString() = "Family(" + nameFamily + ", " + members.getOrElse("<future>") + ")"
}
用法:
scala> val f = new Family("red")
f: Family = Family(red, <future>)
scala> val (p1, p2) = (Person("John", "Smith"), Person("Luis", "Smith"))
p1: Person = Person(John,Smith)
p2: Person = Person(Luis,Smith)
scala> f.setMembers(Set(p1, p2))
scala> f
res1: Family = Family(red, Set(Person(John,Smith), Person(Luis,Smith)))
scala> f.setMembers(Set(p1, p2))
java.lang.IllegalStateException: Promise already completed.
您可以使用类型安全的构建器模式:
case class Person (val name: String, val surname: String)
case class Family (val nameFamily: String, val members: Set[Person])
sealed abstract class TBool
class TTrue extends TBool
class TFalse extends TBool
class FamilyBuilder[WithName <: TBool, WithMembers <: TBool](val nameFamily: Option[String], val members: Option[Set[Person]]) {
def withName(nameFamily: String)(implicit i: WithName =:= TFalse) = new FamilyBuilder[TTrue, WithMembers](Some(nameFamily), members)
def withMembers(members: Set[Person])(implicit i: WithMembers =:= TFalse) = new FamilyBuilder[WithName, TTrue](nameFamily, Some(members))
def create()(implicit i1: WithName =:= TTrue, i2: WithMembers =:= TTrue) = Family(nameFamily.get, members.get)
}
object FamilyBuilder {
def apply() = new FamilyBuilder[TFalse, TFalse](None, None)
}
用法:
scala> FamilyBuilder() withName "Red" withMembers Set(p1, p2) create()
res1: Family = Family(Red,Set(Person(John,Smith), Person(Luis,Smith)))
scala> FamilyBuilder() withMembers Set(p1, p2) withName "Red" create()
res2: Family = Family(Red,Set(Person(John,Smith), Person(Luis,Smith)))
scala> FamilyBuilder() withName "Red" create()
<console>:1: error: Cannot prove that TFalse =:= TTrue.
FamilyBuilder() withName "Red" create()
^