scala - 无法弄清楚 = :=[A, B] 代表什么

标签 scala types

这个问题在这里已经有了答案:




10年前关闭。




Possible Duplicate:
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 必须是 B 的子类型

这些类的一个示例用途是启用在集合中添加数字元素的特化,或定制打印格式,或允许对交易者投资组合中的特定赌注或基金类型进行定制的负债计算。例如:

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 类型的完整短期类(class):http://scalabound.org/?p=323

关于scala - 无法弄清楚 = :=[A, B] 代表什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6422587/

相关文章:

scala - akka 支持高阶 actor 吗?

recursion - 在使用乘积与向量时保持仿函数的积极性

scala - Scala 隐式参数的问题

scala - 使用默认映射 HList

scala - 为什么这些类型参数不符合类型细化?

swift - 如何在 swift 中实现函数特定类型

包含不确定性/误差线的Python数据类型?

C# : Get type parameter at runtime to pass into a Generic method

json - 我应该如何在Scala中指定类似JSON的非结构化数据的类型?

scala - 如何定义与更高种类类型绑定(bind)的上下文(类型构造函数)