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

par*_*tic 12 types scala

可能重复:
Scala 2.8中<:<,<%<和=:=表示什么,它们在哪里记录?

我不明白=:= [A,B]代表什么以及它如何有用.我做了一些研究,但很难找到没有字母字符的东西.有人可以帮我一个真实的例子吗?

Mar*_*sco 11

从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
Run Code Online (Sandbox Code Playgroud)

您可以在这里找到关于Scala类型的完整简短课程:http://scalabound.org/?p = 323

  • @ninjagecko:`a:A`断言_term_`a`有_type_`A` ......它类似于集合论中的"是元素关系(a∈​​A)".`A <:<B`断言_type_ A是_type_ B的子类型,类似于集合论中的子集关系(A⊆B).正如⊆可以用ε定义,我们可以将'A <:<B`解释为命题,"对于所有术语`t`,如果是`t:A`,那么`t:B`". (3认同)