Defining instances of a third-party typeclass, implicit not found but explicit works fine

前端 未结 1 1339
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-29 00:44

I\'m working with Slick\'s GetResult typeclass and wanted to use Shapeless to derive instances of GetResult[Option[(A, B, C...)]]

What I want:

相关标签:
1条回答
  • 2021-01-29 01:22

    The thing is that slick.jdbc.GetResult is covariant. If it were invariant, types would be inferred correctly and implicits would be resolved.

    A workaround is hiding covariant slick.jdbc.GetResult with custom invariant type alias GetResult. Remove import slick.jdbc.GetResult and write in your source file

    type GetResult[T] = slick.jdbc.GetResult[T]
    
    object GetResult {
      def apply[T](implicit f: PositionedResult => T): GetResult[T] = slick.jdbc.GetResult.apply
    }
    

    Now implicitly[GetResult[Option[(Int, Int)]]] compiles. Tested in Scala 2.12.7 + Shapeless 2.3.3 + Slick 3.2.3.

    Variance often makes troubles for implicit resolution:

    https://github.com/scala/bug/issues/10099

    https://github.com/locationtech/geotrellis/issues/1292

    Implicit resolution with covariance

    0 讨论(0)
提交回复
热议问题