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