我在 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) {
}
关于scala - Scala 构造函数和枚举的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7627660/