Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type aliasing a case class in Scala 2.10

Tags:

scala

I'm using Scala 2.10.2, and have two case classes that have identical fields:

case class Foo(id: String, name: String)
case class Bar(id: String, name: String)

I'd like to do something like this:

case class Thing(id: String, name: String)
type Foo = Thing
type Bar = Thing

This compiles, but when I try to create a Foo, I get:

scala> Bar("a", "b")
<console>:8: error: not found: value Bar
              Bar("a", "b")
              ^

Does type aliasing not work with case classes?

like image 549
Josh Glover Avatar asked Feb 17 '14 14:02

Josh Glover


People also ask

What is type alias in scala?

A type alias is usually used to simplify declaration for complex types, such as parameterized types or function types. Let's explore examples of those aliases and also look at some illegal implementations of type aliases.

What does <: mean in scala?

It means an abstract type member is defined (inside some context, e.g. a trait or class), so that concrete implementations of that context must define that type. However, there is a constraint that this type ( Currency ) must actually be a subtype of AbstractCurrency .

What is type in scala?

As you know, a class can have field members and method members. Well, Scala also allows a class to have type members. In your particular case type is, indeed, introducing an alias that allows you to write more concise code. The type system just replaces the alias with the actual type when type-checking is performed.


1 Answers

When you create a case class Scala automatically creates a companion object for it. In your code you define an alias for the type Thing, i.e. for the class Thing only. Your companion object Thing still has only 1 name and no aliases.

One way to "fix" it is to create a reference to the companion object (not a type alias) like this:

scala> val Bar = Thing
Bar: Thing.type = Thing

scala> Bar("a", "b")
res1: Thing = Thing(a,b)

Another way to "fix" it would be to rename the imported object with import package.{Thing => Bar}.

like image 70
yǝsʞǝla Avatar answered Oct 30 '22 18:10

yǝsʞǝla