Scala 使函数接受基于Int的值类型

Scala 使函数接受基于Int的值类型,scala,types,value-type,Scala,Types,Value Type,设想以下Scala值类型: class Prime(val self: Int) extends AnyVal { def +(i: Int): Int = self+i } 如何使我的函数inc接受一个Prime作为它的参数,但也接受任何常规的Int def inc(i: Int): Int = i + 1 现在,我得到以下类型错误: scala> inc(new Prime(2)) <console>:10: error: type mismatch; found

设想以下Scala值类型:

class Prime(val self: Int) extends AnyVal {
  def +(i: Int): Int = self+i
}
如何使我的函数
inc
接受一个
Prime
作为它的参数,但也接受任何常规的
Int

def inc(i: Int): Int = i + 1
现在,我得到以下类型错误:

scala> inc(new Prime(2))
<console>:10: error: type mismatch;
 found   : Prime
 required: Int
       inc(new Prime(2))
           ^
scala>inc(新素数(2))
:10:错误:类型不匹配;
发现:素数
必填项:Int
公司(新首相(2))
^

我正在寻找一种方法来更改
Prime
inc
以允许此函数调用。

Prime
在运行时而不是编译时仅
int
,因此您需要将其转换为int才能实现

implicit def backToInt(p:Prime): Int = p.self

现在您可以传递
inc(新的素数(2))
,它将被隐式转换为int。但是,这会破坏值类型点,即类型安全性。

感谢您的建议。有没有办法将其扩展到在类型参数中使用
Int
?也就是说,为了使它也能与此一起工作:
def sum(is:Iterable[Int])=is.fold(0)(+)
sum(Seq(new Prime(2),new Prime(3))
我想省去键入额外转换的工作量,因为它会分散实际逻辑的注意力。那么,为什么您首先要
Prime