你可以通过定义下面的幻像t YPE:
sealed class DefaultsTo[A, B]
trait LowPriorityDefaultsTo {
implicit def overrideDefault[A,B] = new DefaultsTo[A,B]
}
object DefaultsTo extends LowPriorityDefaultsTo {
implicit def default[B] = new DefaultsTo[B, B]
}
那么你的方法可以写成
def apply[A](id: String)(implicit e: A DefaultsTo String,
processor: Processor[A]) =
processor(data get id)
的overrideDefault
保证,对于任何两个指定的类型,A
和B
,编译器可以始终提供DefaultsTo[A, B]
类型的对象的定义(例如DefaultsTo[Int, String]
)。然而,如果两种类型之一未指定(例如DefaultsTo[A, String]
),编译器将优选识别这两种类型(在该示例中提供DefaultsTo[String, String]
,并因此推断出String
为未指定类型A
)。
作为Naftoli Gugenheim pointed out in this mailing list thread,还可以实现用一些漂亮的语法与语境范围:
class Has[B] {
type AsDefault[A] = A DefaultsTo B
}
def apply[A : Has[String]#AsDefault : Processor](id: String) =
implicitly[Processor[A]].apply(data get id)
请参阅[此问题](http://stackoverflow.com/questions/4403906/is-it-possible-in-scala-to-force-the-caller-to-specify-a-type-parameter-for-a相关技术。 –