Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition with generic type parameter in Scala

Tags:

scala

Hi I am new to scala and trying to write addition program in with 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 this does not work .What mistake i am making .


1 Answers

A could be any type in this case. x + y means x.+(y), which would only compile if either a) the type A had a method +, or b) the type A was implicitly convertible to a type with a method +.

The type scala.Numeric provides the ability to write code that abstracts over the numeric system -- it could be called with Double, Int, or even your own exotic numeric system, such as complex numbers.

You can add an implicit parameter to your method of type Numeric[A].

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

In Scala 2.8, this can be shortened:

object GenericTest extends Application {
  def func1[A: Numeric](x: A, y: A): A = x + y    
}
like image 194
retronym Avatar answered Oct 20 '25 00:10

retronym



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!