can a scala self type enforce a case class type

后端 未结 1 425
别那么骄傲
别那么骄傲 2020-12-11 06:43

Would there be any way in scala, to define a trait\'s self type to be a case class, as in \"any case class\"? I would like a self type to be able to use the .copy

相关标签:
1条回答
  • 2020-12-11 06:46

    This would only work using (as you suggest) structural types, and also only for a fixed known sequence of case class argument types (you need the exact signature of copy). For example:

    trait InCase[Repr] {
      self: { def copy(foo: Int): Repr } =>
    
      def test(foo: Int): Repr = copy(foo)
    }
    
    case class Fail(foo: Int, bar: String) extends InCase[Fail] //illegal inheritance
    
    case class Succeed(foo: Int) extends InCase[Succeed]
    
    Succeed(123).test(456)
    
    0 讨论(0)
提交回复
热议问题