在Scala中表示值的约束的最佳方法?
发布时间:2020-12-16 18:10:34 所属栏目:安全 来源:网络整理
导读:表达Int字段或参数的最佳方式是什么?永远不应该是负面的? 首先想到的是类型的注释,例如案例类Foo(x:Int @NotNegative).但我必须发明自己的注释,并且不会有任何类型的编译时检查或任何东西. 有没有更好的办法? 解决方法 为什么不使用单独的数据类型? cla
表达Int字段或参数的最佳方式是什么?永远不应该是负面的?
首先想到的是类型的注释,例如案例类Foo(x:Int @NotNegative).但我必须发明自己的注释,并且不会有任何类型的编译时检查或任何东西. 有没有更好的办法? 解决方法
为什么不使用单独的数据类型?
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |