问题描述
在Scala中,我可以使用上下文范围:
In Scala, I can use context bounds:
def sort[T : Ordered](t: Seq[T])
表示与以下内容相同的意思:
To mean the same thing as:
def sort[T](t: Seq[T])(implicit def Ordered[T])
如果我有一个带有两个通用参数的类,该怎么办? IE.我希望能够确保我有一个Writer[T, String]
.有没有可以使用上下文边界(T : ...
)的语法,还是我需要显式地包含隐式的(写起来很有趣).
What if I have a class with two generic parameters. I.e. I want to be able to ensure that I have a Writer[T, String]
. Is there a syntax where I can use context bounds (T : ...
) or do I need to have the implicit explicitly (that was fun to write).
推荐答案
是的,有可能!但不是很漂亮:
Yes, it's possible! But not really very pretty:
trait Writer[T, O] {
def write(t: T): O
}
def writeToString[T: ({ type L[x] = Writer[x, String] })#L](t: T) =
implicitly[Writer[T, String]].write(t)
implicit object intToStringWriter extends Writer[Int, String] {
def write(t: Int) = t.toString
}
然后:
scala> writeToString(1)
res0: String = 1
({ type L[x] = Writer[x, String] })#L
称为 lambda类型.有时它们非常方便(如果越野车),但这绝对不是那些时候之一.使用显式隐式功能会更好.
The ({ type L[x] = Writer[x, String] })#L
thing is called a type lambda. Sometimes they're very convenient (if buggy), but this definitely isn't one of those times. You're much better off with the explicit implicit.
这篇关于具有两个通用参数的上下文范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!