我应该如何写一般函数取两个变量并将它们添加到scala中?

时间:2017-02-08 05:23:03

标签: scala

我试过这种方式:

  def add[A](a:A, b:A): A = {
    a + b
  }

编译器说:

  

错误:(47,9)类型不匹配;发现:必需:字符串       a + b

有谁告诉我为什么会发生这个错误?谢谢。

3 个答案:

答案 0 :(得分:8)

实际上,Scala并没有看到Double +和+之间的任何共同点,而且scala通过使用Numeric来保持这种限制。和它的子类如Fractional和Integral。您可以通过以下不同方式开展工作

def addition[T](x: T, y: T)(implicit num: Numeric[T]): T = {
  import num._
  x + y
}

def add[A](x: A, y: A)(implicit numeric: Numeric[A]): A = numeric.plus(x, y)

答案 1 :(得分:0)

在这里,您收到错误是因为compiler无法infer the actual type of variable a and b因此cannot determine如果为+定义了type A方法。

由于您要添加two variables而不只是两个数字,因此您可以在方法中传递anonymous function来定义这些变量之间的perform the addition。通过这种方式,您可以指定添加two stringstwo integers的方式或任何类型的两个参数:

def add[A](a:A,b:A,sum:(A,A)=> A): A = {
    sum(a,b)
  }

add("john","watson", (a:String,b:String) => a.concat(" "+b))
//result: john watson

add(1,2,(a:Int,b:Int) => a + b)
//result: 3

答案 2 :(得分:0)

您可以使用类型类来实现此目的。

首先,为您的操作定义基本特征

trait Addable[T] {
  def +(x: T, y: T): T
}

接下来,为您希望添加的所有类型定义默认含义:

implicit object LongAddable extends Addable[Long] {
  def +(x:Long, y:Long) = x + y
}
implicit object IntAddable extends Addable[Int] {
  def +(x:Int, y:Int) = x + y
}
implicit object StringAddable extends Addable[String] {
  def +(x:String, y:String) = s"${x}${y}"
}

最后,根据您的类型类定义您的方法,使用隐式证据来约束您的参数:

def add[A](a:A, b:A)(implicit ev: Addable[A]): A = {
     ev.+(a,b)
}

将所有这些放在一起允许您使用相同的方法添加Ints,Longs和Strings。

scala> object Example {
     |   trait Addable[T] {
     |     def +(x: T, y: T): T
     |   }
     |   implicit object LongAddable extends Addable[Long] {
     |     def +(x:Long, y:Long) = x + y
     |   }
     |   implicit object IntAddable extends Addable[Int] {
     |     def +(x:Int, y:Int) = x + y
     |   }
     |   implicit object StringAddable extends Addable[String] {
     |     def +(x:String, y:String) = s"${x}${y}"
     |   }
     |   def add[A](a:A, b:A)(implicit ev: Addable[A]): A = {
     |       ev.+(a,b)
     |   }
     | }
defined object Example

scala> Example.add(1,2)
res2: Int = 3

scala> Example.add(1L,2)
res3: Long = 3

scala> Example.add("2", "3")
res4: String = 23