scala - Scala 构造函数和枚举的问题

标签 scala enums constructor

我在 Scala 中有以下类定义:

class AppendErrorMessageCommand private(var m_type: Byte) {

  def this() = this(0x00)

  def this(errorType: ErrorType) = this(getErrorTypeValue(errorType))

  private def getErrorTypeValue(errorType: ErrorType) = {
    if(errorType == USER_OFFLINE)
      0x01
    else if(errorType == PM_TO_SELF)
      0x02

    0x00  
  }
}

ErrorType 是以下枚举:

object ErrorType extends Enumeration {

  type ErrorType = Value
  val USER_OFFLINE, PM_TO_SELF = Value
}

我认为类中的构造函数定义有问题。我的 IDE(这是 Eclipse 的 Scala IDE)告诉我它找不到 getErrorTypeValue。它还告诉我重载的构造函数有其他选择。一个是字节,另一个是枚举。

不过不要太在意 IDE 的这些错误信息。他们可能是错的,因为这经常发生在 IDE 中。但是尽管如此,当 IDE 告诉我有问题时,它通常是错误的。

那么,我的类/构造函数定义有什么问题?

最佳答案

在这种情况下,IDE 是完全正确的,并且与 scala 命令行编译器一致。

你的构造函数接受一个 Byte,所以你需要为它提供一个(0x00 是一个 Int),你需要导入 ErrorType._ 并且你需要将 getErrorTypeValue 移动到伴随对象并声明它返回一个 Byte(推断类型是 Int):

object ErrorType extends Enumeration {
  type ErrorType = Value
  val USER_OFFLINE, PM_TO_SELF = Value
}

import ErrorType._

object AppendErrorMessageCommand {
  private def getErrorTypeValue(errorType: ErrorType): Byte = {
    if(errorType == USER_OFFLINE)
      0x01
    else if(errorType == PM_TO_SELF)
      0x02

    0x00  
  }
}

class AppendErrorMessageCommand private(var m_type: Byte) {
  def this() = this(0x00.toByte)
  def this(errorType: ErrorType) = this(AppendErrorMessageCommand.getErrorTypeValue(errorType))
}

另一种更好的方法是避免使用多个构造函数并使用工厂方法:

object AppendErrorMessageCommand {
  def apply() = new AppendErrorMessageCommand(0x00)
  def apply(b: Byte) = new AppendErrorMessageCommand(b)
  def apply(errorType: ErrorType) = new AppendErrorMessageCommand(AppendErrorMessageCommand.getErrorTypeValue(errorType))

  private def getErrorTypeValue(errorType: ErrorType): Byte = {
    if(errorType == USER_OFFLINE)
      0x01
    else if(errorType == PM_TO_SELF)
      0x02

    0x00  
  }
}

class AppendErrorMessageCommand private(var m_type: Byte) {
}

查看 How can I call a method in auxiliary constructor? 的答案

关于scala - Scala 构造函数和枚举的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7627660/

相关文章:

python - 如何修复 Python Enum - AttributeError(name) from None 错误?

c++ - V8 中的 objects.h 中的 "enum InstanceType"是如何排序的?

c++ - 为什么编译器调用默认构造函数?

c++ - 将元组传递给可变混合类

scala - 我们所有的模型类都应该是案例类吗?

Scala 转换为泛型类型(用于泛型数值函数)

scala - 无法使用 case 类从 Row 的 RDD 创建数据框

scala - 如何加速 scalaz-stream 文本处理?

java - 如何从 JNI 返回枚举

Java抽象类构造函数和new关键字