Conversions and Extensions methods in Scala 3

In Scala 3, if I understand correctly extension methods are translated to labeled functions. This makes them somewhat incompatible with automatic conversions. According to the documentation, Scala 3 will try to to find given conversions of e in

an application e.m(args) with e of type T, if T does define some member(s) named m, but none of these members can be applied to the arguments args.

The problem I have is that Scala 3 does not seem to try conversions when m is an extension method, presumably due to how extension methods are translated. Is there any way I can get around this?

I have a Ring type class, which defines algebraic operations *, +, -on its carriers via extension methods. As the integers are mapped canonically into any given ring, I’d like to be able to treat integers as elements of any ring. Doing it with a conversion like given [R: Ring]: Conversion[Int, R] = n => Ring[R].ZAction(n, Ring[R].one) doesn’t work. For example, if I have a variable x: Polynomial[Rational, "x"] and a given typeclass instance Ring[Polynomial[Rational, "x"]], the expression 3 * x fails to compile with the following error message:

[error] 568 | 3*x
[error] | ^^
[error] |None of the overloaded alternatives of method * in class Int with types
[error] | (x: Double): Double
[error] | (x: Float): Float
[error] | (x: Long): Long
[error] | (x: Int): Int
[error] | (x: Char): Int
[error] | (x: Short): Int
[error] | (x: Byte): Int
[error] |match arguments ((x² :
[error] | Polynomial[Z.Self, ((“x” : String), (“y” : String), (“z” : String)),
[error] | MonomialOrder.GRevLex]
[error] |))
[error] |
[error] |where: x is a reference to a value parameter
[error] | x² is a value locally defined in class PolynomialRingSuite

Something kinda skuffed you can try is:

extension [T](x: T)(using conv: Conversion[T, YourType])
  def yourMethod(...) =
    val correctX = conv(x)
    ...
1 Like

Thanks! I tried something similar to this, but unfortunately I ran into another weird issue regarding resolution of extension methods.