Adding with a generic type parameter in Scala

Hi, I am new to scala and am trying to write an add program with a generic type parameter as shown below

object GenericTest extends Application {
  def func1[A](x:A,y:A) :A = x+y    
    println(func1(3,4))
}

But that will not work. What a mistake I am making.

+3
source share
2 answers

Acan be any type in this case. x + ymeans x.+(y)that will only be compiled if either a) the type Ahad a method +, or b) the type Awas implicitly converted to a type with a method +.

A type scala.Numericprovides the ability to write code that abstracts over a number system β€” it could be called using Double, Int, or even your own exotic number system, such as complex numbers.

Numeric[A].

object GenericTest extends Application {
  def func1[A](x: A, y: A)(implicit n: Numeric[A]): A = x + y    
}

Scala 2.8 :

object GenericTest extends Application {
  def func1[A: Numeric](x: A, y: A): A = x + y    
}
+2
0

Source: https://habr.com/ru/post/1729122/


All Articles