查看将在Scala 2.7.7和2.8脚本中工作的类型类用法示例
大家好,我正在寻找一个在Scala中使用类型类的快速示例,它可以在2.7.7和2.8环境中使用 我看到的所有示例都只在2.8中起作用,但我被告知类型类也可以在2.7.7中实现 唯一的另一个要求是使用必须能够在脚本中工作查看将在Scala 2.7.7和2.8脚本中工作的类型类用法示例,scala,scala-2.8,typeclass,scala-2.7,Scala,Scala 2.8,Typeclass,Scala 2.7,大家好,我正在寻找一个在Scala中使用类型类的快速示例,它可以在2.7.7和2.8环境中使用 我看到的所有示例都只在2.8中起作用,但我被告知类型类也可以在2.7.7中实现 唯一的另一个要求是使用必须能够在脚本中工作 任何例子都感谢!谢谢我想你可以这样做: def max[A](list: List[A])(implicit ord: Ordering[A]): A = { list.tail.foldLeft(list.head) ((a, b) => if (ord.lt(a,
任何例子都感谢!谢谢我想你可以这样做:
def max[A](list: List[A])(implicit ord: Ordering[A]): A = {
list.tail.foldLeft(list.head) ((a, b) => if (ord.lt(a, b)) b else a)
}
implicit def toOrdering[A <% Ordered[A]]: Ordering[A] = new Ordering[A] {
def compare(a: A, b: A): Int = (a < b, b < a) match {
case (true, _) => -1
case (_, true) => 1
case _ => 0
}
}
println(max(List(1, 2, 3, 2, 1)))
defmax[A](列表:列表[A])(隐式命令:排序[A]):A={
list.tail.foldLeft(list.head)((a,b)=>if(ord.lt(a,b))b else a)
}
隐式def toOrdering[A-1
大小写(u,true)=>1
大小写=>0
}
}
println(最大值(列表(1,2,3,2,1)))
代码同时在Scala 2.7.7和2.8.0中运行(目前在这两种版本中都进行了测试),尽管在Scala 2.8中隐式定义是不必要的(在某些情况下可能是有害的)。我采用了以下解决方案:
//---------- Classes without needed behavior
case class Point(x: Double, y: Double)
trait Shape {}
case class Circle(center: Point, radius: Double) extends Shape {}
case class Rectangle(lowerLeft: Point, upperRight: Point) extends Shape {}
val circle = Circle(Point(1.0, 2.0), 5.0)
val rectangle = Rectangle(Point(-2.0, -1.0), Point(4.0, 5.0))
//----------- Support for new behavior I want to add
// Create exception to handle non supported subclasses
case class NewMethodNotSupported(a: Any)
extends RuntimeException(a.toString + ".newMethod() not supported")
class NewBehavior(shape: Shape) {
def newMethod() = shape match {
case c: Circle => doMethod(c)
case r: Rectangle => doMethod(r)
case _ => throw NewMethodNotSupported(shape)
}
private
def doMethod(s: Shape) = println(s) // print to standard out.
}
object NewBehavior {
// invoked by the compiler
implicit def shapeToNewBehavior(s: Shape) = new NewBehavior(s)
}
// bring the implicit method in scope
import NewBehavior._
// --------- End of new behavior support
// Test behavior support:
println("Test that new behavior is added:")
circle.newMethod()
rectangle.newMethod()
// Create a non supported shape class
case class Triangle(vertex1: Point,
vertex2: Point, vertex3: Point) extends Shape {}
val triangle = Triangle(Point(-1.0,0.0), Point(1.0,0.0), Point(0.0,1.0))
// Catch exception thrown by trying to call method from unsupported shape
try{
println("\nTest method call from unsupported shape:")
triangle.newMethod()
} catch {
case dns: NewMethodNotSupported => println(dns); System.exit(-1)
case unknown => println("Uknown exception " + unknown); System.exit(-1)
}
我目前对视图边界不太熟悉,所以我不知道如何使用您的解决方案,但我找到了另一种方法来实现它。这不符合类型类模式。