【问题标题】:Problems with Scala constructors and enumsScala 构造函数和枚举的问题
【发布时间】:2011-10-02 16:33:10
【问题描述】:

我在 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 告诉我有问题时,通常是错误的。

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

【问题讨论】:

    标签: scala enums constructor


    【解决方案1】:

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

    你的构造函数需要一个字节,所以你需要为它提供一个(0x00 是一个 Int),你需要导入 ErrorType._ 并且你需要将 getErrorTypeValue 移动到伴随对象并声明它返回一个字节(推断类型是 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?的答案

    【讨论】:

      【解决方案2】:

      0x00 等是 Int 恰好是十六进制的文字。

      getErrorTypeValue 返回一个Int,所以this(getErrorTypeValue(errorType)) 指的是一个构造函数,它采用了一个不存在的Int

      如果您想将数字文字键入为Byte,请使用0x01: Byte,或指定您的方法的返回类型private def getErrorTypeValue(errorType: ErrorType): Byte = { 以使用隐式转换。

      【讨论】:

        【解决方案3】:

        问题是你不能在委托构造函数时调用getErrorTypeValue,因为对象还没有创建。

        我认为。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-07-03
          • 1970-01-01
          • 2011-08-20
          • 1970-01-01
          • 2011-11-11
          • 2011-10-30
          • 1970-01-01
          相关资源
          最近更新 更多