是否可以通过创建像 PositiveInt 这样的东西来限制 Int 并在 Scala 中进行编译时检查? [英] Is it possible to restrict Int by creating something like PositiveInt and have compile-time checks in Scala?

查看:29
本文介绍了是否可以通过创建像 PositiveInt 这样的东西来限制 Int 并在 Scala 中进行编译时检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个 restricted Int,例如 PositiveInt 并对其进行编译时检查?换句话说,是否可以定义一个方法,例如:

Is it possible to create a restricted Int such as PositiveInt and have compile-time checks for it? In other words is it possible to define a method such as:

def myMethod(x: PositiveInt) = x + 1

然后有类似的东西:

myMethod(-5) // does not compile
myMethod(0)  // does not compile
myMethod(5)  // compiles

如果这是可能的,我应该如何从定义 PositiveInt 开始,我的意思是在 Scala 中有一种方便的技术吗?

If this is possible how should I start with defining PositiveInt, I mean is there a convenient technique for this in Scala?

推荐答案

这种东西叫做依赖类型,不,它在 Scala 中不可用.

This kind of thing is called dependent typing, and no, it's not available in Scala.

这篇关于是否可以通过创建像 PositiveInt 这样的东西来限制 Int 并在 Scala 中进行编译时检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆