在Scala中创建Java枚举 [英] Creating a Java Enum in Scala

查看:205
本文介绍了在Scala中创建Java枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作场所一直在尝试从Java转移到Scala进行一些任务,它对我们正在做的工作很好。然而,一些预先存在的日志记录方法期望一个 java.lang.Enum 。日志记录方法在(Java)基类中定义,子类可以定义自己的枚举,记录器将跟踪多个线程/机器中的所有实例。

My workplace has been experimenting in moving from Java to Scala for some tasks, and it works well for what we're doing. However, some preexisting logging methods expect a java.lang.Enum. The logging method is defined in the (Java) base class, and the subclasses can define their own enums, which the logger will track across all instances in multiple threads/machines.

它在Java中如此工作:

It works like this in Java:

public class JavaSubClass extends JavaBaseClass {
    enum Counters {
        BAD_THING,
        GOOD_THING
    }

    public void someDistributedTask() {
        // some work here
        if(terribleThing) {
            loggingMethod(Counters.BAD_THING)
        } else {
            loggingMethod(Counters.GOOD_THING)
            // more work here
        }
    }
}

然后,当任务完成后,我们可以看到

Then, when the task has finished, we can see that

BAD_THING: 230
GOOD_THING: 10345

是否任何方式通过创建Java 枚举或从 Enumera转换,在Scala中复制此枚举?我已经尝试直接扩展枚举,但似乎是密封的,因为我在控制台中收到错误:

Is there any way to replicate this in Scala, either by creating Java Enums or converting from Enumeration to Enum? I have tried extending Enum directly, but it seems to be sealed, as I get the error in the console:

error: constructor Enum in class Enum cannot be accessed in object $iw
Access to protected constructor Enum not permitted because
enclosing object $iw is not a subclass of 
class Enum in package lang where target is defined


推荐答案

如果需要一个java枚举,那么需要用Java编写它。您可以在Scala中执行以下操作来替换 Enum 用例,但Scala中没有任何复制Java机制的枚举

If you need a java enumeration, then you need to write it in Java. There are things you can do in Scala to replace the use cases of Enum, but there's nothing in Scala that replicates the Java mechanics of Enum.

这篇关于在Scala中创建Java枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆