对 Java 枚举使用类型别名
我想实现类似于scala如何将Map
定义为两者预定义的类型
和对象
的东西。在 Predef
中:
type Map[A, +B] = collection.immutable.Map[A, B]
val Map = collection.immutable.Map //object Map
但是,我想使用 Java enum
(来自共享库)来执行此操作。例如,我有一些全局别名:
type Country = my.bespoke.enum.Country
val Country = my.bespok.enum.Country //compile error: "object Country is not a value"
这样做的原因是我希望能够使用如下代码:
if (city.getCountry == Country.UNITED_KINGDOM) //or...
if (city.getCountry == UNITED_KINGDOM)
但是,在同时导入我的类型别名时这是不可能的。 注意:如果我没有声明预定义类型并导入它,此代码将正常工作!我可以在此处使用一些语法来实现此目的吗?
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 enum
s (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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Scala 中只需使用 import:
对于 Java 使用 静态导入:
In Scala just use import:
And for Java use static import:
Scala 2.8 引入了包对象的概念。 2.7 中 Predef 中的许多内容已移至 scala 包的包对象中。
“如何创建全局别名”形式的问题通常有答案:使用包对象。 (您无法自己创建真正的全局别名,该权力是为 Scala 开发人员保留的,但您可以在您的包及其子包中使用您自己的名称或别名,这要归功于 Scala 中包的真正嵌套性质.)
不幸的是,包对象上没有 SID(Scala 改进文档),但一些有用的链接包括:
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: