在 case class 中将参数 Option[T] 隐式转换为 T

Implicitly convert parameter Option[T] to T in a case class

我有一个案例 class 带有一个选项参数,比方说:

case class Student(id: Option[Int], name: String)

要获取 Student 实例,不仅我可以使用 Student(Some(1), "anderson"),我还希望这种形式是一种有效的方式 Student(2,"Sarah")

我想我必须创建一个 Int => Option[Int] 并将其放在某个地方。那么最好的方法是什么?

更新

如评论中所述,覆盖 apply 方法将阻止 Student.apply _

调用它

在同伴 object 中制作一个 apply 方法可能更容易。

case class Student(id: Option[Int], name: String)

object Student {
  def apply(id: Int, name: String): Student = {
    Student(Some(id), name)
  }
}

使用隐式转换的替代解决方案:

implicit def intToOption(x: Int) = Some(x)
case class Student(id: Option[Int], name: String)

scala> Student(1,"Nu")
res1: Student = Student(Some(1),Nu)