Scala - 为范围内的数字定义类型

Scala - Define types for a number in a range

我想知道我是否可以在 Scala 中定义一个类型,将一个数字包装在一个范围内,并在编译时断言它是有效的。例如:[0,1] 范围内的所有数字,因此我可以定义一个采用 BetweenZeroAndOne 类型的函数。我知道我可以定义一个案例 class holds/wraps 一个数字,然后在运行时检查该数字是否在范围之间,而且我还可以使用隐式转换 Int => BetweenZeroAndOne, Double => BetweenZeroAndOne, BetweenZeroAndOne => Int...但是可以定义0和1之间的数字类型吗?

谢谢,

使用refined:

scala> type ZeroToOne = Not[Less[W.`0.0`.T]] And Not[Greater[W.`1.0`.T]]
defined type alias ZeroToOne

scala> refineMV[ZeroToOne](1.8)
<console>:40: error: Right predicate of (!(1.8 < 0.0) && !(1.8 > 1.0)) failed:
Predicate (1.8 > 1.0) did not fail.

这是可能的解决方案,希望我能正确理解你的问题: 纯粹使用内置 Scala 功能:

object MyInt extends Enumeration {
  type MyInt = Value
  // this is most "fragile" part of this solution
  val Zero, One, Two, Three = Value
}

object MyIntToIntConverter{
  import MyInt._
  implicit def MyIntToInt(x: MyInt) : Int = x.id
  implicit def IntToMyInt(x: Int) : MyInt = MyInt.apply(x)
}

import MyInt._
import MyIntToIntConverter._

val x : Int  = MyInt.Three

val t : MyInt = 3