What is the valueof() function in Scala?

The valueof() function in Scala gets the unique value of any data that is passed to the function. The type only includes the single inhabitant.

We can provide instances of valueof() for any eligible types. We only use instances when we need a runtime value that corresponds to when a type-level computation is needed.

For example, if we want to define a type Residue[A <: Int] that corresponds to a group of A integers, then we can say that the residues can sum up only when the same modulus parameterizes them.

Syntax

final class ValueOf[X] extends AnyVal

Code

enum days:
case Mon, Tue, Wed , Sat, Sun
enum Day ( val name: String)
case Mon extends Day("Monday")
case Tue extends Day("Tuesday")
case Wed extends Day("Wednesday")
case Sat extends Day("Saturday")
case Sun extends Day("Sunday")
def working : Boolean =! (this == Sat || this == Sun)
import Day.*
val sort = Day.values.sortBy(_.ordinal.toSeq)
assert(sort == list(Mon, Tue, Wed, Sat, Sun))
assert(Mon.name == "Monday")
assert(Mon.ordinal == 0)
assert(Mon.valueOf("Mon")) == Day.Mon

In this example, we declare enumeration similar to the declaration of a class. The values allowed are declared with a class.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved