Prohibit generating of apply for case class

前端 未结 3 1026
情书的邮戳
情书的邮戳 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-15 23:55

    If you want to prohibit using some of auto-generated methods of a case class you can define the methods (with proper signature) manually (then they will not be generated) and make them private (or private[this]).

    Try

    object SomeClass {
      type Aux[TT] = SomeClass { type T = TT }
      def apply[TT <: Data](implicit ev: TT =:!= Data): SomeClass.Aux[TT] = new SomeClass() {type T = TT}
      private def apply(): SomeClass = ??? // added
    }
    
    val t: SomeClass = SomeClass() // doesn't compile
    val tt: SomeClass.Aux[Remote.type] = SomeClass.apply[Remote.type] //compiles
    val ttt: SomeClass.Aux[Data] = SomeClass.apply[Data] //doesn't compile
    

    In principle, the methods (apply, unapply, copy, hashCode, toString) can be generated not by compiler itself but with macro annotations. Then you can choose any subset of them and modify their generation as you want.

    Generate apply methods creating a class

    how to efficiently/cleanly override a copy method

    Also the methods can be generated using Shapeless case classes a la carte. Then you can switch on/off the methods as desired too.

    https://github.com/milessabin/shapeless/blob/master/examples/src/main/scala/shapeless/examples/alacarte.scala

    https://github.com/milessabin/shapeless/blob/master/core/src/test/scala/shapeless/alacarte.scala

提交回复
热议问题