Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ambiguous implicit value the only way we want to make the error existed in compilation time

trait Foo

trait Bar extends Foo

def doStuff[T <: Foo](x: T)(implicit ev: T =!:= Foo) = x

doStuff(new Foo{}) //ambiguous implicit value
doStuff(new Bar)// successful

Implicit resolution is happening on compilation time, so in here I think there may be two implicit value with exactly same type to trigger ambiguous stuff.

Right now, I am going to introduce shapeless into the team, my colleagues think this ambiguous implicit is not ideal, and I dont have strong argument about it. Is this only way to do it in order to make type safe in scala. If it is, what can I do to customize the error message ?

Edit:

In the shapeless, I want to make the sum of 2 NAT not equal to 7, I can code like this to make compilation fail.

def typeSafeSum[T <: Nat, W <: Nat, R <: Nat](x: T, y: W)
         (implicit sum: Sum.Aux[T, W, R], error: R =:!= _7) = x

typeSafeSum(_3, _4)

but the error message is ambiguous implicit value, how can I customize the error message ?

like image 547
Xiaohe Dong Avatar asked Jul 24 '14 06:07

Xiaohe Dong


1 Answers

A simple type class would be better than a type inequality test in this (and most other) instance(s).

Presumably the reason for wanting to exclude Foo is that Bar (and its siblings) have some properties which Foo lacks. If that's the case then you should create a type class which captures those properties and make that a requirement on the type argument for doStuff. You can use Scala's @implicitNotFound annotation to make compiler error messages more comprehensible whenever that requirement isn't met.

@annotation.implicitNotFound(msg = "No Props instance for ${T}")
trait Props[T] {
  def wibble(t: T): Double
}

trait Foo
// Note no Props instance for Foo ...

trait Bar extends Foo
object Bar {
  // Props instance for Bar
  implicit def barProps: Props[Bar] = new Props[Bar] {
    def wibble(t: Bar): Double = 23.0
  }
}

def doStuff[T <: Foo](t: T)(implicit props: Props[T]) = props.wibble(t)

scala> doStuff(new Foo {})
<console>:11: error: No Props instance for Foo
              doStuff(new Foo {})
                     ^

scala> doStuff(new Bar {})
res1: Double = 23.0

If there aren't any such properties which distinguish Foo from Bar then you should question your supposition that you need to exclude Foo from doStuff in the first place.

I'd be delighted if you use shapeless in your project, but you should use =!:= (and Scala's own =:=) only as a last resort, if at all.

like image 184
Miles Sabin Avatar answered Sep 23 '22 20:09

Miles Sabin