Robin Khurana
Robin Khurana

Reputation: 109

Scala Object Usage

Is it possible in scala to expose the functionality of a class, based on the condition?

Say

class c(a: Int, b: Int){
  if(a == 1){
     val variable: Int = a
     def function: Int = b
  }

Need to expose variable and function only when a is 1 during the usage of class

Upvotes: 0

Views: 55

Answers (2)

user3237183
user3237183

Reputation:

It is possible with dynamic loading, but there are very few use cases where this would be the right solution.

Many languages support dynamic loading actual modification of the byte code at run-time. The main use-case is to upgrade and modifying applications that cannot stop or cannot be redeployed.

Upvotes: -1

Tim
Tim

Reputation: 27421

No, members must be known at compile time so that access to members can be checked by the compiler.

One option is to use Option:

class c(a: Int, b: Int){
  val variable = if (a==1) Some(a) else None
  def function() = if (a==1) Some(f(b)) else None
}

You can use variable.getOrElse(default) to extract variable from an instance of c.

Another option is to use a class hierarchy

trait C

class B() extends C

class A(a: Int, b: Int) extends C {
  val variable: Int = a
  def function: Int = b
}

object C {
  def apply(a: Int, b: Int): C =
    if (a == 1) {
      new A(a, b)
    } else {
      new B()
    }
}

You create the instance with C(...,...) and when you need to access variable you use match to check that you have an instance of A rather than B.

Upvotes: 2

Related Questions