Pre-SIP: A New Type for Optionals and Error Handling (2)

The flip in type parameters is weird compared to every other result type (Either[A, B], Cats Validated[E, A], ZIO Validation[E, A], Kyo Result[E, A], etc), and every effect type used in Scala. The actual type of Maybe being flipped from the ? syntax sugar could be simply explained as keeping Maybe consistent with how Scala has traditionally ordered ‘result’ types’ parameters. I would rather explain this to a new dev than try to explain why they can’t follow the ordering of Maybe’s type parameters in their own types!

It also keeps the oddness scoped to the part of the spec describing Maybe. Including it in the comparer algorithm requires having that hack specified far removed from where Maybe is defined. (not to mention in the compiler implementation)

It is flipped compared to some languages (eg. Rust Result<T, E>), but the ship sailed on which order Scala uses a long time ago! Trying to turn it around now is just adding more inconsistency.

5 Likes

? is already weird. It allows for one or two arguments. Flipping then those two when lowered into Maybe doesn’t seem like a far call.

We could have a rule that says that any infix type that ends in ? flips the order of arguments. Similar as we have the rule for :, as @mberndt had already mentioned.

Optionally we could have a rule about any infix type that ends in ? sets unapplied parameters to Null. To make this less of a magic trick and more like a proper language feature. This fits with Scala’s long time ethos, spirit and design (see the : precedent).

5 Likes

Yeah, agreed. In the context of Scala’s ecosystem, Maybe[T, E] is the bit that comes across as weird and inconsistent, and seems like a footgun that’s likely to cause minor but real suffering forevermore. We’ve converged on “type to the right” for good reasons, and it’s now a pretty consistent intuition for serious Scala engineers: reversing that is just going to cause constant mental gear-grinding. (As well as Matthias’ more concrete objections.)

By comparison, syntactically flipping T ? E to Maybe[E, T] is basically an implementation detail that the majority of people are never even likely to notice, and the ones who do notice are mostly going to be the ones who appreciate why it’s the right decision.

That said, I do agree with switching T? to be null-based – that’s been my expectation throughout this discussion, and while it matches Scala’s history a bit less, I think it’s immensely pragmatic. Indeed, just yesterday I was in a discussion with one of my teammates where that was basically exactly what we wanted for an interoperability situation, and I was a little chagrined that it doesn’t exist yet.

8 Likes

But every other result type is weird in English.

You generally say “A or B” when you mean that A is the favored outcome, and I think this is the general trend in human languages: a list of alternatives gets the good one first, if there is a good one.

So I found when I stopped using Either[Bad, Good] in favor of Good Or Bad (as an infix type), I had really no problems at all with order. Admittedly, ? is not quite as obvious as Or because with Or you simply say the thing you would normally say in English. Nonetheless, Good ? Bad is pretty natural.

Getting type inference to work in the expected way is important. But the order I think is easily learned because everyone already knows it. The rule is just, “The natural way, not the weird Scala way.”

Now, if we did switch the order, the we would have to have E ? T reduce to ?T. That also reads fine to me. I would not object.

I would object strongly to E ? T reducing to T?. That order-flip is quite nonintuitive, and we have no precedent for that kind of lack of intuitiveness.

3 Likes

Yeah, given the historical conventions of E before T, I like the suggestion of using E ? T and ?T. Still easy to read, and doesn’t have any weirdness that needs to be accounted for (except maybe in the parser).

I am proposing the same as @jducoeur , flip the params to the usual Scala order in Maybe, preserve the readable T ? E ordering in the ? syntax

Alternatively, you could just support A ? B, and have ?B = null ? B and A? = A ? null. Then “bad vs good” or “error vs result” is back to convention and decoupled from the feature implementation.

Though I guess I don’t know how useful that is, since the standard library will probably end up establishing a convention anyway.

1 Like

so the switch was because Err(()) currently print Err(undefined). why can’t we fix ScalaJS ().toString semantics instead.

No this is not about the String representation. It’s about keeping the door open for T ? Unit to be interoperable with JavaScript’s T | undefined.

In Scala.js, () is the JavaScript value undefined. Indeed, that is the value that is returned by methods that return “nothing”. The String representation is therefore very well specified, and needs no “fixing”.

That’s actually an angle that I hadn’t even considered yet. We already have infix type aliases. Type aliases can already flip type parameters. But somehow a flipped infix ? type alias for Maybe is too weird?

1 Like

I don’t think it’s too weird. It’s not very weird to me. It just seems unnecessary.

Keeping things in order is easier than flipping them. This is an argument to keep Either[Bad, Good] aligned with Maybe[Bad, Good], but if Maybe is ?, then it is an even better argument to keep Good ? Bad aligned with Good Maybe Bad i.e. Maybe[Good, Bad].

So I think the same logic comes up twice, with the flip between Maybe and ? the more dubious of the two because of the tighter relationship. (Counterargument: the flip is the difference. Counter-counterargument: yes but you are still obligated to think about the flip.)

So, either disfavored-left all the way through with no change to type resolution: Either[Bad, Good] and Maybe[Bad, Good] and Bad ? Good and ?Good; or the somewhat more natural favored-left but with the break with Either and other constructs that have the other order: Either[Bad, Good] but Maybe[Good, Bad] and Good ? Bad and Good? and a special case for type resolution.

1 Like

The proposed rules allow widening between optional nesting levels (e.g.: Int? <: Int??).
This reduces the compiler’s ability to catch unintended changes in nesting which may lead to subtle bugs.

Example: conflation of nullable data with an optional write operation.

Consider a typed database column and an update API where outer absence means “skip”, while the nullable payload is serialized:

case class Column[T](name: String) // invariant: fixes the stored value type

trait SqlEncoder[T]:
  def encode(value: T): String

object SqlEncoder:
  given SqlEncoder[Int] with
    def encode(value: Int): String = value.toString

  given [T](using encoder: SqlEncoder[T]): SqlEncoder[T?] with
    def encode(value: T?): String = value match
      case null  => "NULL"
      case Ok(v) => encoder.encode(v)

def updateColumn[T](column: Column[T], change: T?)
                   (using encoder: SqlEncoder[T]): Unit =
  change match
    case null => ()
    case Ok(value) =>
      println(
        s"UPDATE users SET ${column.name} = ${encoder.encode(value)} WHERE id = 7"
      )


The database contains age = 42. The user clears the field:

val age = Column[Int?]("age")
val submittedAge: Int? = null // e.g. comes from API request

updateColumn(age, submittedAge)


Intended: write SQL NULL.
Actual: skip the update, leaving 42.

The invariant Column[Int?] fixes T = Int?, so change expects Int??. Nevertheless, the argument is accepted

The schema explicitly permits null data, and the nullable encoder handles it correctly, but that encoder is never called. The argument’s absence is interpreted as “skip” before serialization.

Explicit wrapping gives the intended behavior, but it is not enforced:

updateColumn(age, Ok(submittedAge))
// UPDATE users SET age = NULL WHERE id = 7


Tests covering only non-null inputs will pass, hiding the bug until someone clears a field.

With the equivalent Option API, Column[Option[Int]] would require an Option[Option[Int]] argument and reject an unwrapped Option[Int].
A dedicated update ADT would be clearer for this business case, but nullable fields and partial updates illustrate a practical consequence of this widening.

Mitigation options:
1.
Explore the diagnostics for suspicious widenings, or restrictions that require explicit Ok(value) when embedding an optional payload.

  1. (Unlikely) We could consider prohibiting overlapping optional layers (?? and friends) altogether, but that would sacrifice generic composability:
def map[A, B](fa: F[A])(f: A => B): F[B]


For F[X] = X?, choosing B = Int? requires Int??.
Rejecting that type prevents implementing the ordinary contract;
Silently merging the layers loses information.

1 Like

Suggestions regarding ? syntax and parameter order:

1. Make the most general concept primary

? naturally suggests optionality. Extending it to T ? E makes the general sum look like an extension of optionality, although algebraically the relationship goes the other way: an optional value is a sum with a singleton alternative.

The proposal already captures that relationship semantically but syntax is option-biased.

2. Give disjunction and optionality their own syntax

Both concepts seem important enough to deserve distinct notation:

E \/ T  // general disjunction
T?      // shorthand for Null \/ T


With the underlying constructor also ordered [E, T], this would align surface notation, existing higher-kinded inference, and ecosystem conventions without parameter reversal during desugaring or special inference rules.

Composition preserves different information

Separate syntax makes two distinct constructions clear:

  • (E \/ T)?: an optional choice : absent, left, or right.

  • E? \/ T?: a choice between optional payloads: left absent, left present, right absent, or right present.

The second preserves which branch was selected even when its payload is absent. These are different data models, and distinct syntax makes that difference explicit.

3. Consider a broader tagged-coproduct abstraction (generalize beyond error-handling)
Scala’s mindset was always revolving around building the coherent well-behaved foundations for the future to come, kind of more scientific philosophy, in contrast to other languages that aimed to solve specific corner-case issues in the ad-hoc but practical way which leans more towards engineering philosophy.

Optionality and Error handling are practical and can be important first class language features but the foundations backing them could be more generic.

For example, alternatives Dog, Mammal, and Animal overlap through subtyping.

A tagged sum should still distinguish a dog explicitly embedded in the first, second, or third alternative. The selected branch must survive construction and extraction independently of the payload’s runtime type.

A convenient generic coproduct abstraction (with constant runtime overhead) could be the fundamental basis for Options, Errors and possible other advances usecases.

P.S.:
posting from alt account because my main one was blocked from replies likely because I did several cycles of delete-edit-post of the same message.

1 Like

No, it doesn’t. From the very first description:

Since Int? is not disjoint from Null, it is not true that Int? <: Int??.

1 Like

Please correct me if I’m wrong, but although direct widening does not apply to Int? <: Int??, covariance does:

  1. Widening: Int <: Int? since Int is disjoint from Null.

  2. Covariance :Maybe[Int] <: Maybe[Int?], i.e. Int? <: Int??.

This does not establish T? <: T?? for arbitrary T, but it does whenever T <: T? holds.

For example, this ordinary generic widening would no longer be valid:

def widen[A, B >: A](value: A?): B? = value

Choosing A = Int and B = Int? requires exactly Int? <: Int??.

Uh oh. I think you’re onto something. :grimacing:

T <: T? does not hold for an unconstrained T, because an unconstrained T is not disjoint from Null. But here it seems you can make it a subtype through the bounds.

Then IIUC it’s possible to do:

val x: Int?? = widen[Int, Int?](null)
assert(x != null)
// should be true because (null: Int?) is the Ok case of Int??
// but fails, because `widen` smuggled the null as is, without wrapping in Valid

@odersky Could you have a look at this? It seems covariance must be ruled out in the general case. It could be salvaged for A? <: B? when A is disjoint from Null, but that would be very irregular in the language.

2 Likes

How about reusing the flipping rule we already have:

T ?      // ~ Option[T]
T ?: E   // ~ Either[E, T]/Maybe[E, T]

This would allow the common type parameter ordering (as used by Either and friends), while also allowing the flipped ordering for the short form, since the existing ending-in-colon rule already lets the type associate to the right when written in infix notation.

1 Like

This looks indeed problematic. It seems we cannot allow ? to be covariant in its result, which would be a big restriction.

The condition should probably be B disjoint from Null, otherwise you still get A? <: A??. I think doing this would be feasible. It’s another special case, but ? is special already.

1 Like

I have to ask:
At what point does it become too special ?

From what I have gathered, here are the ways in which this proposal deviates from the Scala norm:

  • Promotes null instead of Option
    • This is a 180 which will lead to ecosystem fragmentation, unless converters are added (which increases the design surface, and can lead to downstream issues)
  • (related to the above) Adds a solution to an already solved problem (the “value of T or nothing” problem)
  • The value for “no result” is null and not () (the Unit value)
  • Is of shape [Good, Bad] instead of [Bad, Good] (although I would not consider this an argument against Good ? Bad)
  • Some typing rules depend on the nullability of the types
  • (the latest) It is only covariant in some specific cases (particularly surprising given it aims to replaceOption/Either which are always covariant)
  • It requires a different feature’s flag to work (it can be surprising that String? requires strict nullability if you don’t know the details)

And again, this is all to solve the issue that Options are not good enough because:

Of which the convenience argument can be addressed by two different, drastically simpler, proposals (the same I have already linked before: 1, 2)

And the efficiency aspect is, as far as I understand, really minor, and requires/causes some of the typing oddities above

4 Likes

Why not drop the widening, instead?

The implicit conversion T => T? has no issues in the general case, even inlined, because it can wrap if it needs to, with runtime detection in the generic case for which static type information is inadequate.

The reason you would want widening is if you want something like Set[Int] <: Set[Int?], so you can play nicely with the covariance of other constructs. But if that breaks the ability of Set[Int]? to stand in for Iterable[Int]?, that would be worse, I would think.