gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:55:11 25 4
gpt4 key购买 nike

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




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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com