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.
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].
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.
=> 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 .
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With