0

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

4
  • 2
    Assume for a moment that this would be somewhat possible. Now imagine I write a function that takes an instance of c, inside that function how would I know that I can (or can't) use either variable or function? I expect that explains why this won't be useful. - Now, why do you want this? What is your use case? What is the bigger picture? Probably there are ways to model what you want to express. Commented Nov 27, 2019 at 3:38
  • The use case is c is being used for two different cases if a == 1 then it is being used for some functionality and else it is used for some different functionality, The thing is c cannot exhibit both the functionalities. Commented Nov 27, 2019 at 3:54
  • 2
    Why not just have two different classes? Why it has to be the same class? Again, how would you use such a class if it is different due a runtime information. Commented Nov 27, 2019 at 4:01
  • The structure/composition of class C is a compile-time property. The value of a (1, -2, 37, whatever) is a run-time property. "...and never the twain shall meet" -Kipling. Commented Nov 27, 2019 at 4:50

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.