开发者

Using type aliases to Java enums

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.开发者_JAVA技巧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?


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:

  • http://www.scala-lang.org/node/1564
  • http://programming-scala.labs.oreilly.com/ch07.html
  • http://blog.objectmentor.com/articles/2009/06/05/bay-area-scala-enthusiasts-base-meeting-whats-new-in-scala-2-8


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};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜