2011-10-02 34 views
2

我有以下的類定義在斯卡拉:問題與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 
    } 
} 

錯誤類型是以下枚舉:

object ErrorType extends Enumeration { 

    type ErrorType = Value 
    val USER_OFFLINE, PM_TO_SELF = Value 
} 

我覺得有什麼不妥在類的構造函數定義。我的IDE(這是Eclipse的Scala IDE)告訴我它找不到getErrorTypeValue。它也告訴我,重載的構造函數有替代。一個是字節,另一個是枚舉。

儘管如此,不要把這些IDE的錯誤信息當回事。他們可能是錯的,因爲這經常發生在IDE中。但是,當IDE告訴我有什麼不對,通常是錯誤的。

那麼,我的類/構造函數定義有什麼問題?

回答

4

在這種情況下,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?

0

問題在於,當委派構造函數時不能調用getErrorTypeValue,因爲該對象尚未創建。

我想。

2

0x00等都是Int碰巧是十六進制的文字。

getErrorTypeValue返回一個Int所以this(getErrorTypeValue(errorType))是指一個構造函數採取Int,它不存在。

如果要鍵入數字文字作爲Byte,請使用0x01: Byte,或者指定方法private def getErrorTypeValue(errorType: ErrorType): Byte = {的返回類型以使用隱式轉換。