【发布时间】:2011-09-19 08:06:42
【问题描述】:
可能重复:
What do <:<, <%<, and =:= mean in Scala 2.8, and where are they documented?
我不明白 =:=[A,B] 代表什么以及它有什么用处。我做了一些研究,但很难搜索其中没有字母字符的东西。有人可以帮我举一个真实的例子吗?
【问题讨论】:
-
抱歉重复,但同样,无法搜索字符串“=:="...
可能重复:
What do <:<, <%<, and =:= mean in Scala 2.8, and where are they documented?
我不明白 =:=[A,B] 代表什么以及它有什么用处。我做了一些研究,但很难搜索其中没有字母字符的东西。有人可以帮我举一个真实的例子吗?
【问题讨论】:
从 Scala 2.8 开始,参数化类型通过通用类型约束类获得了更多的约束能力。这些类可以进一步专门化方法,并补充上下文边界,如下所示:
A =:= B 断言 A 和 B 必须相等
A <: b a>
这些类的一个示例用法是启用专门化以在集合中添加数字元素,或用于定制打印格式,或允许对交易者投资组合中的特定投注或基金类型进行自定义责任计算。例如:
case class PrintFormatter[T](item : T) {
def formatString(implicit evidence: T =:= String) = { // Will only work for String PrintFormatters
println("STRING specialised printformatting...")
}
def formatPrimitive(implicit evidence: T <:< AnyVal) = { // Will only work for Primitive PrintFormatters
println("WRAPPED PRIMITIVE specialised printformatting...")
}
}
val stringPrintFormatter = PrintFormatter("String to format...")
stringPrintFormatter formatString
// stringPrintFormatter formatPrimitive // Will not compile due to type mismatch
val intPrintFormatter = PrintFormatter(123)
intPrintFormatter formatPrimitive
// intPrintFormatter formatString // Will not compile due to type mismatch
您可以在此处找到有关 Scala 类型的完整短期课程:http://scalabound.org/?p=323
【讨论】:
<:< 与: 有何不同?
a:A 断言 term a 具有 type A...类似于“是集合论中关系 (a ∈ A) 的一个元素。 A <:< B 断言 type A 是 type B 的子类型,类似于集合论中的子集关系 (A ⊆ B)。正如 ⊆ 可以用 ∈ 定义一样,我们可以将 A <:< B 解释为命题,“对于所有术语 t,如果 t:A,则 t:B”。
=:=[A,B] 类是 A 和 B 属于同一类的证据。参见例如http://apocalisp.wordpress.com/2010/06/10/type-level-programming-in-scala-part-2-implicitly-and/ 解释一下。
很难找到一些例子。这是一点点代码:
【讨论】:
最好的办法是查看 Predef 的来源。在那里你可以找到:
object =:= {
implicit def tpEquals[A]: A =:= A = new (A =:= A) {def apply(x: A) = x}
}
因此,A =:= B 类型的对象只有在 A 和 B 是相同类型时才隐式可用。
【讨论】:
=:=[A, A]的对象。它没有解释A =:= A 的含义。