How to delay assignment of class values in Scala?

scala declare variable without initializing
scala local variables must be initialized
scala global variable
scala lazy var
a variable requires an initial value to be defined
scala lazy val
scala var vs val
how to print the variable in scala

I have a class that gets created using data a read from a .conf file. The class also contains a value b which does not come from the conf file.

The class:

case class Configuration(a: String, b: String)

The sequence of calls to instantiate a Configuration looks like this:

User -> ConfigurationCompiler -> ConfigurationReader -> readConfig(): Configuration (The user gets a Configuration object back)

Value a gets read and set by the .conf file, but value b is specified by the user. I don't want to pass value b all the way down to readConfig() so it can be set on instantiation of Configuration.

I have experimented with Option, but to me it looks ugly because you first instantiate b with None, and then set it later. Also, the tests look weird because you must test Some(String) instead of String. Option also doesn't seem like it fits here because the field is actually not optional, it is just set at a later time.

The Option class:

case class Configuration(a: String, var b: Option[String])

Some solution might be to use implicit, but implicit String doesn't look good - implicit types are resolved by type, so it should be something less general than String.

What I can think of is something like PartialConfiguration returned by readConfig(). Then you can add it's values to the values provided by User to create full Configuration.

How to assign a Scala class field to a (lazy) block or function , You want to initialize a field in a Scala class using a block of code, or by calling a function. Solution. Set the field equal to the desired block of  Re: Re assignment to Val Immutable values can't be changed, ever, this is by design. It might first look like you cant doing a lot of things, but to see how this idea works it helps to think about the way that numbers behave.

You could create the original configuration object with a default value in the b position. When you get the actual value of b, then create a copy that is used by your program using:

val realConfig = originalConfig.copy( b = bValue )

The copy will have the field b replaced with the desired value for actual use.

[PDF] Programming in Scala, 4 First-Class Functions. 29 Web services address the message delay prob- whole class hierarchy, not just values of a single type. Rational conforms to AnyRef, so it is legal to assign a Rational value to a variable. This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 4.8, “How to assign a Scala class field to a block or function.” Problem. You want to initialize a field in a Scala class using a block of code, or by calling a function. Solution. Set the field equal to the desired block of code or function.

I would go for a builder. Here's an example:

import cats.implicits._
import cats.data.ValidatedNel

case class ConfigBuilder(a: Option[String] = None, b: Option[String] = None) {
  def withA(a: String): ConfigBuilder = copy(a = Some(a))
  def withB(b: String): ConfigBuilder = copy(b = Some(b))
  def build: ValidatedNel[String, Configuration] =
    (a.toValidNel("'a' must be defined"), b.toValidNel("'b' must be defined"))
      .mapN(Configuration)
}

Validating both fields:

ConfigurationBuilder()
  .build
// Invalid(NonEmptyList('a' must be defined, 'b' must be defined))

Getting valid configuration:

ConfigurationBuilder()
  .withA("test")
  .withB("test2")
  .build
// Valid(Configuration(test,test2))

initializing later, to be later (and something has to be there):. class Test { // will hold a Foo class lazy val foo = null. def validate(bar:SomeFactory) { if (test == null)  You can extend a base Scala class and you can design an inherited class in the same way you do it in Java (use extends key word), but there are two restrictions: method overriding requires the override keyword, and only the primary constructor can pass parameters to the base constructor. Let us extend our above class and add one more class method.

Scala Basic Tutorial, 6 Case Classes and Pattern Matching. 51 Web services address the message delay prob- lem by increasing granularity, Rational conforms to AnyRef, so it is legal to assign a Rational value to a variable of type AnyRef:. You want to provide a default value for a Scala constructor parameter, which gives other classes the option of specifying that parameter when calling the constructor, or not. Solution Give the parameter a default value in the constructor declaration.

Using the Timer and TimerTask Classes, In this Scala Tutorial, you will learn the basics of Scala such as how to declare tutorial, immutability is a first class citizen in the Scala programming language. variable named donutsToBuy of type Int and assign its value to 5. Sometimes you may wish to delay the initialization of some variable until at  You can also assign the results from a Scala if expression in a simple function, like this absolute value function: As shown, the Scala if/then/else syntax is similar to Java, but because Scala is also a functional programming language, you can do a few extra things with the syntax, as shown in the last two examples.

Scala Programming Projects: Build real world projects using , is an example of using a timer to perform a task after a delay: import java.util. public class Reminder { Timer timer; public Reminder(int seconds) { timer = new  The comparison of pattern matching decomposition approach (using scala trait and case class) with the object oriented approach (trait and class implementations) is highlighted in Expr.scala, Expr2.scala, and Expr3.scala.

Comments
  • I think this is the simplest solution that doesn't use defaults which I feel are not elegant if you intend to set them later. I like this approach because it gives back a complete object, that is explicitly stated as being a PartialConfiguration, instead of a Configuration with implied missing parts.
  • @jcallin Do you have to be able to inspect the PartialConfiguration objects? If not, you could just use a function ConfInput => UserInput => Configuration directly, without inventing any new classes to hold intermediate results. If you define Configuration in the simplest way possible as case class Configuration(a: String, b: String), then the function (confStr: String) => (userStr: String) => Configuration(confStr, userStr) of type String => String => Configuration seems sufficient.