开发者

Restrict Constructor Access

开发者 https://www.devze.com 2023-03-25 07:59 出处:网络
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] =

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 outsid开发者_开发知识库e of its companion. Is that possible in Scala?


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消