Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict Constructor Access

Tags:

oop

scala

I have a type like this

sealed class Foo[A](val value: A)

object Foo {
    def apply[A](v: A)(implicit num: Numeric[A]): Foo[A] =
      /* highly complex stuff to make a Foo[A] */

    implicit def toA[A](x: Foo[A]) = x.value
}

Foo as a class is only supposed to hold the value, so an implicit Numeric would not make much sense. But I need the type of A to be always a numeric.

So my idea is to just make it impossible to use Foos normal constructor outside of its companion. Is that possible in Scala?

like image 551
Lanbo Avatar asked Apr 08 '26 04:04

Lanbo


1 Answers

Yeah, since the companion object can access private members of its companion class you can just make the primary (and auxiliary if any) constructor private. Pseudo code here:

class ConcreteFoo private (n: Int) extends Foo(n)
like image 134
agilesteel Avatar answered Apr 09 '26 23:04

agilesteel