如何将参数默认设置为Scala中另一个参数的值?

时间:2015-01-11 17:35:32

标签: scala

为什么我不能执行以下操作:

def multiply(a: Int, b: Int = a) = a * b

case class Point(x: Int, y: Int = x)

还有另一种方法可以达到同样的目的吗?我需要这个的原因是因为有时候,具有不同值的参数更多是例外而不是规则。举个例子:

case class User(name: String, age: String, description: String, displayName: String = name, online: Boolean = false)

在90%的情况下,显示名称和名称应该相同,但在少数边缘情况下,它不应该。将一个参数默认为另一个参数的值将非常有用。有没有办法做到这一点?如果没有,为什么?

2 个答案:

答案 0 :(得分:1)

是。参数列表中的参数可以引用先前参数列表中的参数值,类似于类型推断可以引用先前参数列表中的类型:

def multiply(a: Int)(b: Int = a) = a * b

case class Point(x: Int)(y: Int = x)

case class User(name: String, age: String, description: String)(displayName: String = name, online: Boolean = false)

应该有用。

答案 1 :(得分:1)

一种方法是将案例类定义为

case class User(name: String, age: String, description: String, displayName: String, online: Boolean = false) {
    def this(name: String, age: String, description: String, online: Boolean = true) =
    this(name, age, description, name, online)
}

然后您可以创建案例类

  val user = new User("User name", "5", "description")
  //> user  : User = User(User name,5,description,User name,true)
  user.displayName
  //> res0: String = User name
  val userWithDisplayName = new User("User name", "5", "description", "displayName")
  //> userWithDisplayName  : User = User(User name,5,description,displayName,false)

您还可以覆盖随播对象中的apply方法。这样您就不必在创建对象之前编写新内容


scala> :paste
// Entering paste mode (ctrl-D to finish)
case class User(name: String, age: String, description: String, displayName: String, online: Boolean = false)
object User {
  def apply(name: String, age: String, description: String, online: Boolean) =
    new User(name, age, description, name, online)
}
// Exiting paste mode, now interpreting.
defined class User
defined module User
scala> User("User name", "5", "description", "displayName")
res0: User = User(User name,5,description,displayName,false)
scala> User("User name", "5", "description", true)
res1: User = User(User name,5,description,User name,true)