【发布时间】:2017-12-11 05:59:48
【问题描述】:
我正在执行以下函数以从另一个返回一个新图形,但 Scala 将结果推断为 Figure 并且我希望它特别是图形,作为一个圆圈等。 我该怎么做才能推断出特定的数字?我被告知使用泛型来解决它,这是怎么回事?
trait Figure {
def x:Int
def y:Int
}
case class Circle(x:Int, y: Int, radio: Double)
extends Figure
case class Rectangle(x:Int, y: Int, width: Int, high: Int)
extends Figure
object Motor {
def move[T](x: Int, y: Int, figure: T) :Figure = figure match {
case Circle(xPos, yPos, radio) => Circle(xPos+x, yPos+y, radio)
case Rectangle(xPos, yPos, width, high) => Rectangle(xPos+x, yPos+y, width, high)
}
}
【问题讨论】:
-
那么......这段代码有什么问题?除了 Circulo 和 Rectangulo 中的拼写错误(这些是拼写错误吗?)
-
我假设您在谈论
move是Figure而不是像 Circle 或 Rectangle 这样的具体类的结果。要访问底层的具体类,您可以像在上面的方法中那样使用模式匹配。 -
@SarveshKumarSingh 函数 move 返回图,但我想特别将图返回为圆形、矩形等。
-
@ThePretendProgrammer 这正是我想要的,但是函数的结果是 Figure 并且我希望它是特定的图形,现在我通过在测试中进行转换来解决它但我想要函数一个人做。
标签: scala