Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Failed attempt to get rid of boilerplate in methods using Numeric[T]
// Sorry Predef, we want '+' back!
import Predef.{any2stringadd => _, _}
object test {
{
trait MyNumeric[T] extends Ordering[T] {
def plus(x: T, y: T): T
//
// Made this implicit
//
implicit def fromInt(x: Int): T
class Ops(lhs: T) {
//
// Use view bounds here.
//
def +[TT <% T](rhs: TT) = plus(lhs, rhs)
}
implicit def mkNumericOps(lhs: T): Ops = new Ops(lhs)
}
object MyNumeric {
implicit val IntNumeric: Numeric[Int] = null
}
{
def foo1[T: MyNumeric](t: T): T = {
val nt = implicitly[MyNumeric[T]]; import nt._ // Ugly boiler plate!
t + 2
}
}
object MyNumericOps {
@inline implicit def ops[T](t: T)(implicit nt: MyNumeric[T]): MyNumeric[T]#Ops = nt.mkNumericOps(t)
implicit def tFromInt[T](t: Int)(implicit nt: MyNumeric[T]): T = nt.fromInt(t)
}
{
import MyNumericOps._
def foo2[T: MyNumeric](t: T): T = {
t + tFromInt(2) // this works
// compiler tries infers ops[T](t).+(2)(tFromInt[Nothing] _), and fails with: "could not find implicit value for parameter nt"
t + 2
0: T
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.