user79074
user79074

Reputation: 5270

How to pass a parameter to a lazy val

I have a scenario where I want to pass a parameter when accessing a lazy value. The example below should explain the problem. Can someone recommend the best way to achieve this?

Thanks Des

class A(test: Boolean) {

}

object A {

  lazy val a = new A(???)

  def apply(test: Boolean) = a(test)
}

Can of course be achieved using var and Option but wondering if there is a better way:

class A(test: Boolean) {

}

object A {

  var a: Option[A] = None

  def apply(test: Boolean) = a match {
    case Some(sa) => sa
    case None => 
      a = Some(new A(test))
      a.get
    }
}

Upvotes: 2

Views: 2998

Answers (2)

Gabriele Petronella
Gabriele Petronella

Reputation: 108101

The companion object is a singleton, so initializing its constant values (val and lazy val) using an external parameter doesn't really make sense.

If you need a different value for every instance, then move the lazy val to the class as such

class A(test: Boolean) {
    lazy val a = test
}

Otherwise just use a def

object A {
    def a(test: Boolean) = new A(test)
    def apply(test: Boolean) = a(test)
}

Upvotes: 1

Ende Neu
Ende Neu

Reputation: 15783

You could pass the type to a:

class A(test: Boolean) { }

object A {

  lazy val a: A.type = A

  def apply(test: Boolean): A = a(test)
}

Although I don't see the point to be honest.

Upvotes: 1

Related Questions