Reputation: 141
I have two files, Vec3.scala
and Main.scala
. In Vec3.scala
, I define the Vec3
case class that implements all sorts of nice operators like +
, unary_-
, dot product, and so on. Since I will be using both colors and points in the project I am working on, my C++ instincts want me to type alias Vec3
as Color
and Point3
like so:
// Vec3.scala
package vec3
final case class Vec3(x: Float, y: Float, z: Float) {
...math functions...
}
type Color = Vec3
type Point3 = Vec3
However, when I attempt to compile using sbt
, I get the following error that I somewhat expected:
expected class or object definition
type Color = Vec3
^
I assume this is because these type aliases do not reside in a class or object, but I don't want them to since I would much prefer Color
and Point3
to have the same ease of use as Vec3
itself. If I was using C++, I'd just put these definitions in a header file and call it a day, but alas. Is there a way to do this in Scala, without having the users of my vec3
package make these type aliases themselves every time they are used in a file? Or is there some nifty Scala maneuver that solves this problem in a different way?
Upvotes: 1
Views: 1839
Reputation: 12102
type aliases can't exist outside of a class, trait or object in scala 2. Define them in the package object instead.
Upvotes: 6