0

I have this sample code:

val someCondition = true
case class SampleClass (source: String)

val sample: SampleClass

if (someCondition)
  sample = new SampleClass("Some String")
else
  sample = new SampleClass("Other String")

I want to define a val argument and initialize it based on some condition. but I can't figure out how to do that. also, if I change it to var I still can't.

1

2 Answers 2

6

In Scala if is an expression, which means it evaluates to some value, hence you can do the following:

val sample = if (someCondition) new SampleClass("Some String")
             else new SampleClass("Other String")
Sign up to request clarification or add additional context in comments.

Comments

3

You can do as follows.

val sample: SampleClass = {
  if (someCondition) new SampleClass("Some String")
  else new SampleClass("Other String")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.