Search code examples
scalashrinkscalacheck

Shrink macro for case class


I'm implementing Shrink instances for my case classes. It seems to me that a macro could do the job. Has someone implemented one yet?


Solution

  • Yes, they have! shapeless-contrib has an instance of Shapeless's TypeClass for Shrink:

    scala> import org.scalacheck._
    import org.scalacheck._
    
    scala> case class Foo(s: String, i: Int)
    defined class Foo
    
    scala> val unshrunk = Foo("This is a very long string", 1000)
    unshrunk: Foo = Foo(This is a very long string,1000)
    
    scala> implicitly[Shrink[Foo]].shrink(unshrunk) // boring default instance
    res0: Stream[Foo] = Stream()
    
    scala> import shapeless.contrib.scalacheck._
    import shapeless.contrib.scalacheck._
    
    scala> implicitly[Shrink[Foo]].shrink(unshrunk) // interesting instance
    res1: Stream[Foo] = Stream(Foo(This is a ver,1000), ?)
    

    This is supported by macros, but only the ones that Shapeless uses for its Generic machinery.