4

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 .

andri
  • 11,171
  • 2
  • 38
  • 49
  • You really have to say a lot more about what you're trying to accomplish and what precisely you tried. – Randall Schulz Jan 19 '10 at 19:50
  • This is effectively a duplicate of http://stackoverflow.com/questions/485896/how-does-one-write-the-pythagoras-theorem-in-scala. – Daniel C. Sobral Jan 19 '10 at 22:44
  • Hi thanks for your answer . Randall -I was just trying to play with generic type and try to use '+' operator over everything i passed to function like string+string ,int+int,double+double –  Jan 21 '10 at 10:00

2 Answers2

4

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    
}
retronym
  • 54,768
  • 12
  • 155
  • 168
  • Thanks this helped a lot .But i guess i have scala 2.7 on my machine which does not have scala.Numeric Class. –  Jan 21 '10 at 10:01
  • It is a new addition in 2.8. http://harrah.github.com/browse/samples/library/scala/Numeric.scala.html – retronym Jan 21 '10 at 10:43
0

Go to Scala: How to define “generic” function parameters? for what you want.

Community
  • 1
  • 1
Eastsun
  • 18,526
  • 6
  • 57
  • 81