gpt4 book ai didi

scala - 标记类型与类扩展 AnyVal

转载 作者:行者123 更新时间:2023-12-03 01:33:01 26 4
gpt4 key购买 nike

为了引入更多类型安全性,我们可以使用 shapeless 提供的标记类型或创建一个扩展 AnyVal 的类。使用其中一种与另一种相比有什么区别和优点/缺点?

示例:

trait CountryCodeTag
type CountryCode = String @@ CountryCodeTag

class CountryCode(code: String) extends AnyVal

最佳答案

类型 CountryCode = String @@ CountryCodeTag

+ String @@ CountryCodeTagString 的子类型,即 String 中的所有方法都可以直接使用:countryCode。改为大写

String @@ CountryCodeTag 可能会在需要某些 String 的地方意外使用,即它的类型安全性较低。

− 创建新值有点尴尬:"a".asInstanceOf[String @@ CountryCodeTag]val tagger = new Tagger[CountryCodeTag];标记器(“a”)

− 对 Shapeless 的依赖(尽管这可以手动完成)。

class CountryCode(code: String) extends AnyVal

+ 类型更加安全。

- 通过一些额外的努力即可使用来自String的方法:

class CountryCode(val code: String) extends AnyVal
new CountryCode(countryCode.code.toUpperCase)

class CountryCode(val code: String) extends AnyVal 
object CountryCode {
def unapply(...) = ...
}
countryCode match { case CountryCode(code) => new CountryCode(code.toUpperCase) }

case class CountryCode(code: String) extends AnyVal
countryCode.copy(code = countryCode.code.toUpperCase)

+ 创建新值更自然一些:new CountryCode("a")

+ 没有额外的依赖项(它是纯 Scala)。

关于scala - 标记类型与类扩展 AnyVal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46748075/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com