在 Scala 中表示值约束的最佳方式?

发布于 2024-10-08 15:33:09 字数 160 浏览 0 评论 0原文

表达 Int 字段或参数永远不应该为负数的最佳方式是什么?

首先想到的是类型上的注释,例如 case class Foo(x: Int @NotNegative)。但我必须发明自己的注释,并且不会有任何类型的编译时检查或任何东西。

有更好的办法吗?

What is the best way to express that, say, an Int field or parameter should never be negative?

The first thing that comes to mind is an annotation on the type, like case class Foo(x: Int @NotNegative). But I'd have to invent my own annotation, and there wouldn't be any sort of compile-time checking or anything.

Is there a better way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

や三分注定 2024-10-15 15:33:09

为什么不使用单独的数据类型?

class Natural private (val value: Int) {
   require(value >= 0)

   def +(that:Natural) = new Natural(this.value + that.value)
   def *(that:Natural) = new Natural(this.value * that.value)
   def %(that:Natural) = new Natural(this.value % that.value)
   def |-|(that:Natural) = Natural.abs(this.value - that.value) //absolute difference

   override def toString = value.toString
}

object Natural {
  implicit def nat2int(n:Natural) = n.value
  def abs(n:Int) = new Natural(math.abs(n))
}

用法:

val a = Natural.abs(4711)
val b = Natural.abs(-42)
val c = a + b
val d = b - a  // works due to implicit conversion, but d is typed as Int
println(a < b) //works due implicit conversion

Why not using a separate data type?

class Natural private (val value: Int) {
   require(value >= 0)

   def +(that:Natural) = new Natural(this.value + that.value)
   def *(that:Natural) = new Natural(this.value * that.value)
   def %(that:Natural) = new Natural(this.value % that.value)
   def |-|(that:Natural) = Natural.abs(this.value - that.value) //absolute difference

   override def toString = value.toString
}

object Natural {
  implicit def nat2int(n:Natural) = n.value
  def abs(n:Int) = new Natural(math.abs(n))
}

Usage:

val a = Natural.abs(4711)
val b = Natural.abs(-42)
val c = a + b
val d = b - a  // works due to implicit conversion, but d is typed as Int
println(a < b) //works due implicit conversion
落叶缤纷 2024-10-15 15:33:09

也许稍微好一点(?),但仍然没有编译器检查:require(x >= 0)

Slightly better (?), perhaps, but still no compiler check: require(x >= 0).

冷夜 2024-10-15 15:33:09

Scala 目前不支持契约和不变量。

Contracts and invariants are not supported by Scala at this time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文