Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

In my recent adventures in Scala, I've found case classes to be a really nice alternative to enums when I need to include a bit of logic or several values with them. I often find myself writing structures that look like this, however:

object Foo{
  case class Foo(name: String, value: Int, other: Double)

  val BAR = Foo("bar", 1, 1.0)
  val BAZ = Foo("baz", 2, 1.5)
  val QUUX = Foo("quux", 3, 1.75)

I'm primarily worried here about the naming of the object and the case class. Since they're the same thing, I end up with Foo.Foo to get to the inner class. Would it be wise to name the case class something along the lines of FooCase instead? I'm not sure if the potential ambiguity might mess with the type system if I have to do anything with subtypes or inheritance.

share|improve this question

2 Answers 2

up vote 2 down vote accepted

The nested Class Foo.Foo is not the same class as Foo and there is no ambiguity. The case class Foo (the inner one) can only be accessed by it's complete name (Foo.Foo). But:

If you 'import Foo._' or 'Foo.Foo' you will run into trouble. One Solution is to use

import Foo.{Foo => InnerFoo}

Or you don't import anything and use the complete Path (Foo and Foo.Foo). Does this answer you question?

share|improve this answer
Yes, I think so. I was running into confusion and trouble by importing Foo._. Didn't think to alias it. –  KChaloux Aug 29 '12 at 20:30

In Scala there exist package objects. Thus, there is no need for searching a new name:

package foo {
  case class Foo(name: String, value: Int, other: Double)
package object foo {
  val Bar = Foo("bar", 1, 1.0)
  val Baz = Foo("baz", 2, 1.5)
  val Quuz = Foo("quux", 3, 1.75)

Later you can import them with:

import foo._
// use all members of package `foo` and package object `foo`

Btw, constants are usually named UpperCamelCase (as shown in my example).

share|improve this answer
Ah, neat. Didn't know about these. +1 for enlightening me to something that seems helpful, if not immediately then at least in the near future. –  KChaloux Aug 29 '12 at 20:31

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.