Skip to content

Instantly share code, notes, and snippets.

@retronym
Created February 6, 2010 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retronym/296654 to your computer and use it in GitHub Desktop.
Save retronym/296654 to your computer and use it in GitHub Desktop.
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