Closed as not planned
Description
The "planets" example at https://docs.scala-lang.org/scala3/book/types-adts-gadts.html#algebraic-datatypes-adts compiles but fails to run. Tested on MacOS with Scala 3.2.2.
Code copied from example:
enum Planet(mass: Double, radius: Double):
private final val G = 6.67300E-11
def surfaceGravity = G * mass / (radius * radius)
def surfaceWeight(otherMass: Double) = otherMass * surfaceGravity
case Mercury extends Planet(3.303e+23, 2.4397e6)
case Venus extends Planet(4.869e+24, 6.0518e6)
case Earth extends Planet(5.976e+24, 6.37814e6)
object Planet:
def main(args: Array[String]) =
val earthWeight = args(0).toDouble
val mass = earthWeight / Earth.surfaceGravity
for (p <- values)
println(s"Your weight on $p is ${p.surfaceWeight(mass)}")
Output:
(base) djb@MacBook-Pro-10 scala % scalac bad_planets.scala
(base) djb@MacBook-Pro-10 scala % scala bad_planets.scala 100
Internal error: Detected the following main methods:
(Planet,public static void Planet.main(java.lang.String[]))
(Planet$$anon$3,public static void Planet.main(java.lang.String[]))
(Planet$$anon$1,public static void Planet.main(java.lang.String[]))
(Planet$$anon$2,public static void Planet.main(java.lang.String[]))
Working alternative code:
enum Planet(mass: Double, radius: Double):
private final val G = 6.67300E-11
def surfaceGravity = G * mass / (radius * radius)
def surfaceWeight(otherMass: Double) = otherMass * surfaceGravity
case Mercury extends Planet(3.303e+23, 2.4397e6)
case Venus extends Planet(4.869e+24, 6.0518e6)
case Earth extends Planet(5.976e+24, 6.37814e6)
@main def main(earthWeight: Double): Unit =
val mass = earthWeight / Planet.Earth.surfaceGravity
for (p <- Planet.values)
println(s"Your weight on $p is ${p.surfaceWeight(mass)}")
Output:
(base) djb@MacBook-Pro-10 scala % scalac planets.scala
(base) djb@MacBook-Pro-10 scala % scala planets.scala 100
Your weight on Mercury is 37.775761520093525
Your weight on Venus is 90.49990998410455
Your weight on Earth is 100.0
The book explains that the sample is intended to illustrate that an enum
can have a companion object:
Like classes and
case
classes, you can also define a companion object for anenum
The revised code above does not illustrate that point, and therefore is not an equivalent example. On the other hand, the current example does not appear to run and the revision, which does run, does illustrate how to walk over the enumeration and interact with it.
Metadata
Metadata
Assignees
Labels
No labels