可以解构导致未来的错误吗?

时间:2017-07-28 08:41:25

标签: scala destructuring

最初,我们有一个像

这样的代码
class Person(firstName: String, lastName: String)

val (firstName, lastName) = person

有人交换字段

class Person(lastName: String, firstName: String)

val (firstName, lastName) = person

编译器很高兴!

1 个答案:

答案 0 :(得分:5)

编译器无法知道您交换了字段的顺序,因为分析没有查找参数 name 。只要typer类型检查,一切都很好。您可以做的是另外一种类型:

case class FirstName(name: String)
case class LastName(name: String)

class Person(firstName: FirstName, lastName: LastName)

现在交换类型会导致编译时错误。

如果您不想要分配其他对象的额外费用,请查看shapeless tagged types

import shapeless.tag.@@

trait FirstNameTag
trait LastNameTag

type FirstName = String @@ FirstNameTag
type LastName = String @@ LastNameTag

case class Person(fn: FirstName, ln: LastName)

现在:

import shapeless.tag

val firstName: FirstName = tag[FirstNameTag][String]("yuv")
val lastName: LastName = tag[LastName][String]("itz")

val person = Person(firstName, lastName)

或@Ren指出使用value classes

case class FirstName(name: String) extends AnyVal
case class LastName(name: String) extends AnyVal