Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基本类型的Scala类型上限_Scala - Fatal编程技术网

基本类型的Scala类型上限

基本类型的Scala类型上限,scala,Scala,我是Scala新手,我想编写一个重载运算符的泛型类。但我想将类型限制为Int、Long和Double。是否可以为基元类型创建类型上限 这是我为Int所做的。我需要使这个类成为泛型的,它应该只接受Int、Long和Double。如果这不是正确的方法,我希望有人能为这个问题提供另一种解决方案 class MyClass(value: Int) { def +(operand: Int): MyClass = { return new MyClass(value+operand);

我是Scala新手,我想编写一个重载运算符的泛型类。但我想将类型限制为Int、Long和Double。是否可以为基元类型创建类型上限

这是我为Int所做的。我需要使这个类成为泛型的,它应该只接受Int、Long和Double。如果这不是正确的方法,我希望有人能为这个问题提供另一种解决方案

class MyClass(value: Int) {
  def +(operand: Int): MyClass = { 
    return new MyClass(value+operand);
  }

  def -(operand: Int): MyClass = {
    return new MyClass(value-operand);
  }

  def *(operand: Int): MyClass = {
    return new MyClass(value*operand);
  }

  def /(operand: Int): MyClass = {
    return new MyClass(value/operand);
  }
} 
你可以用这个。我需要隐式的
MyClassOperators[T]
在作用域中,并且只为所需的
Int
Long
Double
实现它

定义实现操作的特征:

object MyClassImplicits {
  trait MyClassOperators[T <: AnyVal] {
    def +(firstOperand: T, secondOperand: T): MyClass[T]

    def -(firstOperand: T, secondOperand: T): MyClass[T]

    def *(firstOperand: T, secondOperand: T): MyClass[T]

    def /(firstOperand: T, secondOperand: T): MyClass[T]
  }
并更改
MyClass
的定义,以要求隐式
MyClassOperators[T]
在范围内:

class MyClass[T <: AnyVal : MyClassOperators](val value: T) {
    def doSomeAddition(otherValue: T): MyClass[T] = {
      implicitly[MyClassOperators[T]].+(value, otherValue)
    }
}
收益率:

3
但当我们使用
Double
实例(尚未实现)进行尝试时:


非常感谢。这似乎是一个很好的解决方案。我会试试看,然后接受这个答案。
def main(args: Array[String]): Unit = {
  val myClassOfInt = new MyClass[Int](1)
  println(myClassOfInt.doSomeAddition(2).value)
}
3
[error] could not find implicit value for evidence parameter of type tests.NewTest.MyClassImplicits.MyClassOperators[Double]
[error]     val myClassOfInt = new MyClass[Double](1.0)
[error]                        ^
[error] one error found