【问题标题】:Cannot figure out what =:=[A,B] stands for [duplicate]无法弄清楚 =:=[A,B] 代表什么 [重复]
【发布时间】:2011-09-19 08:06:42
【问题描述】:

可能重复:
What do <:<, <%<, and =:= mean in Scala 2.8, and where are they documented?

我不明白 =:=[A,B] 代表什么以及它有什么用处。我做了一些研究,但很难搜索其中没有字母字符的东西。有人可以帮我举一个真实的例子吗?

【问题讨论】:

  • 抱歉重复,但同样,无法搜索字符串“=:="...

标签: scala types


【解决方案1】:

从 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

【讨论】:

  • 那么&lt;:&lt;: 有何不同?
  • @ninjagecko: a:A 断言 term a 具有 type A...类似于“是集合论中关系 (a ∈ A) 的一个元素。 A &lt;:&lt; B 断言 type A 是 type B 的子类型,类似于集合论中的子集关系 (A ⊆ B)。正如 ⊆ 可以用 ∈ 定义一样,我们可以将 A &lt;:&lt; B 解释为命题,“对于所有术语 t,如果 t:A,则 t:B”。
【解决方案2】:

【讨论】:

  • 你能举例说明如何使用它吗?
【解决方案3】:

最好的办法是查看 Predef 的来源。在那里你可以找到:

object =:= {
  implicit def tpEquals[A]: A =:= A = new (A =:= A) {def apply(x: A) = x}
}

因此,A =:= B 类型的对象只有在 A 和 B 是相同类型时才隐式可用。

【讨论】:

  • 但这是一个使用=:=[A, A]的对象。它没有解释A =:= A 的含义。
  • 它确实告诉您编译器如何隐式获取 A=:=B 的实例,这是该类的唯一用途。 only 类作为 A 等于 B 事实的见证人。
猜你喜欢
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-21
相关资源
最近更新 更多