Factory methods of case classes

Try making the case class abstract

abstract case class Foo(s: () => String)

object Foo:
  def apply(s: => String) = new Foo(() => s) {}

val x = Foo("woohoo")
// x: Foo = Foo(repl.MdocSession$$$Lambda$9836/833363921@408a20be)
x.s()
// res0: String = woohoo
val Foo(s) = x
// s: Function0[String] = repl.MdocSession$$$Lambda$9836/833363921@408a20be
s()
// res1: String = woohoo

Note how the pattern matching still works.

2 Likes