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?
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.
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 .
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.
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}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With