Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I write general function take two variable and add them in scala?

Tags:

scala

I tried this way:

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

The compiler says:

Error:(47, 9) type mismatch; found : A required: String a + b

Any one tell me why this error happened? Thank you.

like image 910
Kai Liu Avatar asked Feb 08 '17 05:02

Kai Liu


People also ask

How do you pass variables in Scala?

Scala allows you to indicate that the last parameter to a function may be repeated. This allows clients to pass variable length argument lists to the function. Here, the type of args inside the print Strings function, which is declared as type "String*" is actually Array[String].

How do you use function as a variable in Scala and what is the usage?

Use def to define a method, val to create a function. When assigning a function to a variable, a function literal is the code on the right side of the expression. A function value is an object, and extends the FunctionN traits in the main scala package, such as Function0 for a function that takes no parameters.

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

Why is val better than VAR in Scala?

The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable. Because val fields can't vary, some people refer to them as values rather than variables.


1 Answers

Actually Scala doesn't see any common grounds between a Double's + and a an Int's + and also scala keeps this restriction by using Numeric. and its subclasses like Fractional and Integral. You can do your work in different ways like below

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

or

def add[A](x: A, y: A)(implicit numeric: Numeric[A]): A = numeric.plus(x, y)
like image 83
Dilan Avatar answered Oct 12 '22 15:10

Dilan