Since a method-level annotation can be accomplished with a typeclass, but everyone agrees that using typeclasses would be too verbose, perhaps we could make typeclasses more ergonomic? One thing that has always bothered me about typeclasses in Scala is that in the (reasonably common) case where you don’t care about the type, you still have to name it:
def foo[T: Typeclass](x: T): Unit = {...only accesses methods via Typeclass[T] ...}
In Rust, you don’t have to name the type:
fn foo(x: impl Typeclass) { ... }
This is why the Into pattern works so well:
fn foo(x: impl Into<Int>) { ... }
is more verbose than the proposed x: into Int
, but it’s not a special language construct.
We could do something in similar in Scala, but more powerful. Suppose that in addition to being able to ascribe a type to a parameter, we could also ascribe a type lambda TL
, where the semantics are
def foo(x: TL)
is syntactic sugar for
def foo[T](x: T)(using TL[T])
Then, we could write the very first definition as
def foo(x: Typeclass[_]): Unit = { ... only uses methods on Typeclass ... }
Similarly, for implicit conversions, you could write
def foo(x: Conversion[_, Int]): Unit = { ... }
This is still pretty verbose, but with a succinct alias for Conversion
like Into
, it’s actually less verbose than Rust
def foo(x: Into[_, Int]): Unit
If we want to get really fancy, we could even use an operator like =:>
and infix types to get
def foo(x: _ =:> Int): Unit = { ... }
but that’s probably too much and I don’t even know if it parses.
This is maybe too radical of a proposal, but if you agree with the premise that it would be nice to make typeclasses lightweight enough that they can be used without modification for method-level implicit conversions, then it’s maybe worth thinking through other options.
And yes, I’m well aware that this will proposal will be very confusing given the recently changed meaning of _
in types. It will have to wait for 3.2 at a minimum, and even then the potential for confusion might be too great. I don’t want to focus too much on this specific proposal, just argue that something like it might solve not just the problem at hand, but also make typeclasses easier to use in general.