加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 使用值类(没有方法)和类型别名是否有优势?

发布时间:2020-12-16 09:51:49 所属栏目:安全 来源:网络整理
导读:假设我有这个ADT: case class Person(id: String)case class Kid(id: String,name: String) 我想以更明确和类型安全的方式表示id字段.我有两个选择 1.输入别名 type PersonId = Stringcase class Person(id: PersonId)case class Kid(id: String,name: Pers
假设我有这个ADT:

case class Person(id: String)
case class Kid(id: String,name: String)

我想以更明确和类型安全的方式表示id字段.我有两个选择

1.输入别名

type PersonId = String
case class Person(id: PersonId)
case class Kid(id: String,name: PersonId)

价值等级

case class PersonId(id: String) extends AnyVal
case class Person(id: PersonId)
case class Kid(id: String,name: PersonId)

哪种方法比较惯用?
在这种情况下使用值类是否有任何优点(没有其他方法)?

解决方法

类型别名纯粹是语法上的便利 – 在某些情况下,它们可以使代码更清晰或更容易重构,但它们不提供任何额外的类型安全性.例如,假设我有一些这样的代码:

type DegreesC = Double
type DegreesF = Double

def c2f(c: DegreesC): DegreesF = (c * 9.0 / 5.0) + 32

并且代表华氏温度当前温度的值:

val currentTempInF = 62.0

编译器很高兴让我把它传递给我的c2f方法:

scala> c2f(currentTempInF)
res1: DegreesF = 143.6

值类为您提供更多的类型安全性,而不需要为案例类额外分配的运行时成本(尽管仍有语法成本):

case class DegreesC(value: Double) extends AnyVal
case class DegreesF(value: Double) extends AnyVal

def c2f(c: DegreesC): DegreesF = DegreesF((c.value * 9.0 / 5.0) + 32)

val currentTempInF = DegreesF(62.0)

然后:

scala> c2f(currentTempInF)
<console>:14: error: type mismatch;
 found   : DegreesF
 required: DegreesC
       c2f(currentTempInF)
           ^

您更喜欢的是品味问题.我个人认为Scala中的类型别名经常被过度使用和超卖,但我也倾向于避免使用值类,因为它们有奇怪的限制和错误,并且它们提供的运行时性能优势对我来说并不重要.在任何情况下,我都不会说一种方法或另一种更惯用(如果我将这种状态赋予普通的非价值类案例类).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读