user2066880 user2066880 - 3 months ago 22
Scala Question

Generic factory (?) pattern in Scala

I have a generic class:

class SomeValue[T](private val value: T) {
override def toString = value.toString
}


In my application, I'm going to be using a particular construction of this class a lot:

val five = new SomeValue[Int](5) // doing this a lot
assert(five.toString == "5")


This is pretty verbose and prone to typos (for example setting it to 6 by accident). To solve this, I'd like to create a class that masks this pattern:

class Five { ... }


So that I can now do this:

val five = new Five
assert(five.toString == "5")


Kind of a dumb example I know, but hope you get the picture!

Answer

It seems like you are building constants, hence I would suggest using Scala objects.

e.g.

object Main extends App {
  assert(Five.toString == "5")
  assert(Hello.toString == "hello")
}

class SomeValue[T](private val value: T) {
  override def toString = value.toString
}

object Five extends SomeValue[Int](5)
object Hello extends SomeValue[String]("hello")