Michal Rus
Michal Rus

Reputation: 1848

Require user to provide [Type] in Scala's method?

If I write something along the lines of:

class A

class B {
  def add[T <: A]() = { ... }
}

Then how do I require a user to provide the type T when he calls B.add? These two calls compile:

class C extends A

class D extends A {
  val b = new B
  b.add()      // 1.
  b.add[C]()   // 2.
}

I'd like 1. to generate compile-time error instead of defaulting to b.add[D]().

Is that possible?

Upvotes: 2

Views: 104

Answers (1)

senia
senia

Reputation: 38045

You could use =!= evidence from this answer to enforce difference between A and T like this:

def add[T <: AnyRef](implicit e: T =!= AnyRef) = null.asInstanceOf[T]

scala> add
<console>:10: error: ambiguous implicit values:
 both method equal in trait LowerPriorityImplicits of type [A]=> =!=[A,A]
 and method nequal in object =!= of type [A, B](implicit same: =:=[A,B])=!=[A,B]
 match expected type =!=[T,AnyRef]
              add
              ^

scala> add[String]
res1: String = null

Upvotes: 7

Related Questions