gpt4 book ai didi

Scala:在类型别名不匹配时强制编译错误

转载 作者:行者123 更新时间:2023-12-04 11:37:29 25 4
gpt4 key购买 nike

在分配共享相同基础类型的不同类型别名时,有没有办法获得编译时错误(或至少警告)?

换句话说,假设我有这个代码:

type Address = String
type City = String

def foo(x:Address) = ...

如果我这样做,我想获得编译时错误/警告:
val city: City = "Dublin"
foo(city)

据我所知,编译器允许它,因为它们是相同的底层类型。

最佳答案

据我所知,不可能获得您为类型别名寻求的这种“类型安全”。但是,还有一种替代类型别名可用于您的需要:Value Classes .基本上,值类可以在不分配新对象的情况下为您提供类型。请注意,对于类型别名没有的值类有一些限制。
引用 Scala 文档:

Correctness

Another use case for value classes is to get the type safety of a data type without the runtime allocation overhead. For example, a fragment of a data type that represents a distance might look like:

  class Meter(val value: Double) extends AnyVal {
def +(m: Meter): Meter = new Meter(value + m.value)
}

Code that adds two distances, such as

  val x = new Meter(3.4)
val y = new Meter(4.3)
val z = x + y

will not actually allocate any Meter instances, but will only use primitive doubles at runtime.

关于Scala:在类型别名不匹配时强制编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26714627/

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