Skip to content
This repository was archived by the owner on Jun 5, 2023. It is now read-only.
This repository was archived by the owner on Jun 5, 2023. It is now read-only.

More powerful implicit resolution in case matches #242

@adampauls

Description

@adampauls

Consider the following code (compiled with 3.1.0-RC2):

object Test {
  
  trait Foo[Self]

  case class Impl1(a: String)
  given Foo[Impl1] with {}
  case class Impl2(b: Int)
  given Foo[Impl2] with {}

  object Foo {
    class Type private (t: Any)

    object Type {
        def apply[T: Foo](t: T) = new Type(t)
        def unapply[T: Foo](t: Type): Option[T] = ???
    }
  }

  val x = Foo.Type(Impl1("x"))
  val matched: Option[Impl2] = Foo.Type.unapply(x) // compiles
  val matchedNoType = Foo.Type.unapply(x) // ambiguous implicit arguments (understandable)
  x match {
    case Foo.Type(_: Impl2) => ??? // ambiguous implicit arguments (could do better)
    case Foo.Type(Impl2(_)) => ??? // ambiguous implicit arguments (could do better)
  }
}

In the above, Foo.Type.unapply takes an implicit type parameter that only shows up on the output. When directly invoking unapply in a context where the expected type constrains the output type, everything works. However, in a case match where the output type of unapply is effectively constrained by a nested matcher, implicit resolution still fails.

I'm not sure if there is a good reason for this. In cases where the nested unapply and/or type ascription unambiguously specifies a type constraint, I think implicit resolution could be successful.

Of course there are ambiguous cases -- for example, if we have

case Foo.Type(SomeAmbiguousUnapply(_)) => ???

where SomeAmbiguousUnapply has both unapply(Impl1) and unapply(Impl2), there is insufficient information to constrain the implicit search and it's reasonable to fail in that case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions