gpt4 book ai didi

scala - Scala 中的类型推断和泛型

转载 作者:行者123 更新时间:2023-12-01 13:27:36 24 4
gpt4 key购买 nike

我正在执行以下函数以从另一个函数返回一个新图形,但 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)
}
}

最佳答案

这是 Sarvesh Kumar Singh 关于使用类型类的建议的一个更简洁的版本,也许不那么令人生畏。我认为这是最好的方法。它为您提供类型安全功能,同时让您的基本类型非常简单。

trait Figure {
def x:Int
def y:Int
}
case class Circle(x:Int, y: Int, radius: Double) extends Figure

case class Rectangle(x:Int, y: Int, width: Int, height: Int) extends Figure

trait Movable[T] {
def move( x: Int, y: Int, movable: T ) : T
}
implicit final object CircleIsMovable extends Movable[Circle] {
def move( x: Int, y: Int, c: Circle ) = Circle( c.x + x, c.y + y, c.radius )
}
implicit final object RectangleIsMovable extends Movable[Rectangle] {
def move( x: Int, y: Int, r: Rectangle ) = Rectangle( r.x + x, r.y + y, r.width, r.height )
}
object Motor {
def move[T : Movable](x: Int, y: Int, movable: T) : T = implicitly[Movable[T]].move( x, y, movable )
}

然后...

scala> Motor.move(10,10,Circle(0,0,1))
res1: Circle = Circle(10,10,1.0)

scala> Motor.move(10,10,Rectangle(0,0,1,1))
res2: Rectangle = Rectangle(10,10,1,1)

关于scala - Scala 中的类型推断和泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47747225/

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