Hi all, I had a go at translating the following Haskell
data Circle = Circle Float
data Rect = Rect Float Float
class Shape a where
area :: a -> Float
instance Shape Circle where
area (Circle r) = pi * r^2
instance Shape Rect where
area (Rect length' width') = length' * width'
main = do
putStrLn (show (area(Circle 1)))
putStrLn (show (area(Rect 2 3)))
to Scala:
case class Circle(radius: Float)
case class Rect(width: Float, height: Float)
sealed trait Shape[A]:
def area(shape: A): Double
object Shape:
given circleShape: Shape[Circle] with
def area(circle: Circle): Double =
math.Pi * circle.radius * circle.radius
given rectShape: Shape[Rect] with
def area(rect: Rect): Double =
rect.width * rect.height
import Shape.given
assert(circleShape.area(Circle(1)) == math.Pi)
assert(rectShape.area(Rect(2,3)) == 6)
When invoking the area function, I am having to specify which of the two versions I mean to invoke, because if I do this:
import Shape.circleShape._
import Shape.rectShape._
assert(area(Circle(1)) == math.Pi)
assert(area(Rect(2,3)) == 6)
I get this:
import Shape.circleShape._
35
import Shape.rectShape._
36
assert(area(Circle(1)) == math.Pi)
Reference to area is ambiguous,
it is both imported by import Shape.circleShape._
and imported subsequently by import Shape.rectShape._
Found: Circle
Required: Rect
37
assert(area(Rect(2,3)) == 6)
Reference to area is ambiguous,
it is both imported by import Shape.circleShape._
and imported subsequently by import Shape.rectShape._
Any ideas as to whether trying to achieve the above makes sense and is possible?