Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detail UnapplyInvalidReturnType error message #17167

Merged
merged 1 commit into from
May 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion compiler/src/dotty/tools/dotc/reporting/messages.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1962,7 +1962,11 @@ class UnapplyInvalidReturnType(unapplyResult: Type, unapplyName: Name)(using Con
|To be used as an extractor, an unapply method has to return a type that either:
| - has members ${Magenta("isEmpty: Boolean")} and ${Magenta("get: S")} (usually an ${Green("Option[S]")})
| - is a ${Green("Boolean")}
| - is a ${Green("Product")} (like a ${Magenta("Tuple2[T1, T2]")})
| - is a ${Green("Product")} (like a ${Magenta("Tuple2[T1, T2]")}) of arity i with i >= 1, and has members _1 to _i
|
|See: https://docs.scala-lang.org/scala3/reference/changed-features/pattern-matching.html#fixed-arity-extractors
|
|Examples:
|
|class A(val i: Int)
|
Expand Down
14 changes: 14 additions & 0 deletions tests/neg/17077.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
case class IsIntResult()

object IsInt:
def unapply(x: Int): IsIntResult = IsIntResult()

@main def test =
val v: String | Int = "Blop"
val res =
v match
case IsInt() => 43 // error: cannot use a product of arity zero as a return type for unapply
// see UnapplyInvalidReturnType in messages.scala
// and https://docs.scala-lang.org/scala3/reference/changed-features/pattern-matching.html#fixed-arity-extractors
case _ => 42
println(res)
20 changes: 20 additions & 0 deletions tests/pos/17077.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class MyProduct extends Product:
def foo = ???
override def productArity: Int = 1
override def productElement(n: Int): Any = 42
override def canEqual(that: Any): Boolean = that.isInstanceOf[MyProduct]
def _1 = 42

object MyProductUnapply:
def unapply(x: Int): MyProduct = MyProduct()

@main def test =
val v: String | Int = "Blop"
val res =
v match
case MyProductUnapply(y) => y // works: a product of arity 1 is accepted as the return type of unapply
// see UnapplyInvalidReturnType in messages.scala
// and https://docs.scala-lang.org/scala3/reference/changed-features/pattern-matching.html#fixed-arity-extractors
case _ => 42
println(res)