Type coercion for union types in contravariant position #25112
Replies: 1 comment 2 replies
-
|
yes so the error in your scenario is: -- [E007] Type Mismatch Error: -------------------------------------------------
5 |val b: Option[Int] => Boolean = foo(bar, baz)
| ^^^^^^^^^^^^^
| Found: None.type | Some[Int] => Boolean
| Required: Option[Int] => Boolean
|
| longer explanation available when compiling with `-explain`which is confirmed by scala> summon[((Some[Int] | None.type) => Boolean) <:< (Option[Int] => Boolean)]
-- [E172] Type Error: ----------------------------------------------------------
1 |summon[((Some[Int] | None.type) => Boolean) <:< (Option[Int] => Boolean)]
| ^
|Cannot prove that Some[Int] | None.type => Boolean <:< Option[Int] => Boolean.
1 error foundso the arguments what facilities exist? i guess implicit conversion which might be what you are asking for, to convert a "sum" type into the union of its child instantiations - but of course this isnt very general and only works when the union type covers every case im also sure that the type theory experts would not be happy to break the lattice and make Option <:< Some | None |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I've noticed that if I construct a function like the following:
Where
AandBare in contravariant positions.Then when I provide
AandBto be a subtype of a common supertypeC(like a sealed trait),A <: C, B <: C, such thatA | Bwould cover the entirety ofC. (e.g. A: Some[P], B: None.type, C: Option[P])Then Scala would give
bto be(None.type | Some[Int]) => Boolean, which is expected. But when I try to typebto beOption[Int] => Boolean, the compiler would throw an error, claiming it should be a Boolean when it found what was give before.I bring up the contravariant case because for the covariant case, type coercion does occur and Scala allows
bto be coerced intoCtype, seeming to imply that theCtype is somehow a subtype of the union of its "case" types within the implementation.Would it make sense for the union of all case types of a sealed trait to have/ automatically derive some type evidence between them instead of a subtyping relation?
Beta Was this translation helpful? Give feedback.
All reactions