tags:

views:

497

answers:

2

I would like to achieve something similar to how scala defines Map as both a predefined type and object. In Predef:

type Map[A, +B] = collection.immutable.Map[A, B]
val Map = collection.immutable.Map //object Map

However, I'd like to do this using Java enums (from a shared library). So for example, I'd have some global alias:

type Country = my.bespoke.enum.Country
val Country = my.bespok.enum.Country //compile error: "object Country is not a value"

The reason for this is that I'd like to be able to use code like:

if (city.getCountry == Country.UNITED_KINGDOM) //or...
if (city.getCountry == UNITED_KINGDOM)

Howver, this not possible whilst importing my type alias at the same time. Note: this code would work just fine if I had not declared a predefined type and imported it! Is there some syntax I can use here to achieve this?

A: 

In Scala just use import:

import mypackage.Country
import mypackage.Country._

val c = Country.FRANCE
// With pattern matching:
c match {
  case UK => println("UK")
  case FRANCE => println("FRANCE")
}
// Or with an if:
if (c == FRANCE) println("FRANCE")

And for Java use static import:

package mypackage;

import static mypackage.Country.*;

public class Test {
    public static void main(String[] args) {
        Country c = UK;
        if (c == FRANCE) {
            System.out.println("Ok");
        }
    }
}

enum Country {FRANCE, UK};
Alexandre Pauzies
Alexandre - this is a **Scala** question - not a Java one!
oxbow_lakes
Changed the answer for Scala
Alexandre Pauzies
+3  A: 

Scala 2.8 introduces the concept of package objects. A lot of the stuff that was in Predef in 2.7 has been moved to the scala package's package object.

Questions of the form "how do I make a global alias" often have the answer: use package objects. (You can't make a truly global alias yourself, that power is reserved for the Scala developers, but you can make your own name or alias available throughout one of your packages and its subpackages, thanks to the truly nested nature of packages in Scala.)

Unfortunately there isn't a SID (Scala Improvement Document) on package objects, but some helpful links include:

Seth Tisue