0
我经常想通过使用类型别名避免在scala中创建新的类。但我也需要一些静态方法来处理这些类型。 考虑下面的例子为CardValue类型:Scala:输入对象的别名
package object cards {
/**
* Type representing card values from 2 to A
*/
type CardValue = Byte
}
object CardValue {
/**
* Creates CardValue
*
* @param value value index from 0 (2) o 12(A)
* @tparam T any Numeric type which can be converted to Byte
* @return new CardValue
*/
def apply[T <% Byte](value: T): Card = {
require(value >= 0 && value < 13, "Wrong card value index. CardValue is enumeration from 0 to 12.")
value
}
/**
*
* @return Correct string for card value
*/
override def toString: String = {
case 8 => "T"
case 9 => "J"
case 10 => "Q"
case 11 => "K"
case 12 => "A"
case x: Number => (x.byteValue() + 2).toString
}
}
目前有两个问题与此代码: 1.它不会编译 2.我不知道该代码将作为我的计划(例如它将从对象调用toString而不是来自Byte)。
我是不是这样做了所有错误的方法,并输入别名不能像这样使用?
这有用,谢谢,它回答了我所有的问题。另外,您需要删除对象实现。案例类带有默认应用方法 – GrayR
您是对的。我会把你的'require'移到它所属的case类。 –