Prohibit generating of apply for case class

前端 未结 3 1038
情书的邮戳
情书的邮戳 2021-02-15 23:47

I\'m writing a type-safe code and want to replace apply() generated for case classes with my own implementation. Here it is:

import shap         


        
3条回答
  •  长发绾君心
    2021-02-16 00:14

    So you can make the constructor private and ensure that T is also something different to Nothing.

    I believe the best way to ensure the constructor is private (as well as many other things as @MateuszKubuszok show) is to use a (sealed) trait instead of a class:
    (if you can not use a trait for whatever reasons, please refer to Mateusz's answer)

    import shapeless._
    
    sealed trait Data
    final case object Remote extends Data
    final case object Local extends Data
    
    sealed trait SomeClass {
      type T <: Data
    }
    
    object SomeClass {
      type Aux[TT] = SomeClass { type T = TT }
      def apply[TT <: Data](implicit ev1: TT =:!= Data, ev2: TT =:!= Nothing): Aux[TT] =
        new SomeClass { override final type T = TT }
    }
    

    Which works like this:

    SomeClass() // Does not compile.
    SomeClass.apply[Remote.type] // Compiles.
    SomeClass.apply[Data] // Does not compile.
    

    You can see it running here.

提交回复
热议问题