我有这个案例课:
case class MyCaseClass(left:Long, right: Long = Option[Long], operator: Operator = Option[Operator]){
def inRange(outer: Long) = outer >= left && outer <= right
}
这是我尝试实例化的方法:
val instance = MyCaseClass(leftValue)
但是我得到一个编译错误:
未指定的值参数权限,运算符
这个错误是什么意思?我只想为一个案例类提供两个构造函数:一个带有三个参数,另一个带有一个参数。
这有效(如Ende Neu所建议的):
case class MyCaseClass(left:Long, right: Option[Long] = None, operator: Option[Operator] = None)
问题是,我要包right
和operator
在Option
。以下内容使您可以避免Option
对right
和operator
参数进行换行(有关更多详细信息,请参见答案):
object MyCaseClass {
def apply(left: Long, right: Long, operator: Operator) = new MyCaseClass(left, Option(right), Option(operator))
}
您没有传递默认值,而是传递了类型,如果要传递默认参数,则必须指定一些值:
scala> case class Operator(operation: String)
defined class Operator
scala> case class MyCaseClass(left:Long, right: Long = 0L, operator: Operator = Operator("+")){
| def inRange(outer: Long) = outer >= left && outer <= right
| }
defined class MyCaseClass
scala> val instance = MyCaseClass(10L)
instance: MyCaseClass = MyCaseClass(10,0,Operator(+))
如果要包装它们,Option
则必须声明它们:
case class MyCaseClass(left:Long, right: Option[Long] = None, operator: Option[Operator] = None)
在我用作None
值的地方,您也可以使用Some
并将一些默认值传递给它们。
如果您不希望用户使用选项创建完整的对象,请创建一个伴随对象并定义一个新的apply方法:
case class Operator(operation: String)
object MyCaseClass {
def apply(left: Long, right: Long, operator: Operator) = new MyCaseClass(left, Option(right), Option(operator))
}
case class MyCaseClass(left:Long, right: Option[Long] = None, operator: Option[Operator] = None)
您现在可以用不同的方式构造对象:
MycaseClass(10L)
MycaseClass(10L, Option(10L), Option(Operator("+"))
MycaseClass(10L, 20L, Operator("+"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句