Scala构造函数和枚举的问题

use*_*561 3 enums constructor scala

我在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  
  }
}
Run Code Online (Sandbox Code Playgroud)

ErrorType是以下枚举:

object ErrorType extends Enumeration {

  type ErrorType = Value
  val USER_OFFLINE, PM_TO_SELF = Value
}
Run Code Online (Sandbox Code Playgroud)

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

但是不要认真对待IDE的这些错误消息。它们可能是错误的,因为这在IDE中经常发生。但是,尽管如此,当IDE告诉我有什么问题时,通常是错误的。

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

Mat*_*ell 5

在这种情况下,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))
}
Run Code Online (Sandbox Code Playgroud)

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

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) {
}
Run Code Online (Sandbox Code Playgroud)

请参阅“ 如何在辅助构造函数中调用方法”的答案