# Type polymorphism misunderstanding

4 messages
Open this post in threaded view
|
Report Content as Inappropriate

## Type polymorphism misunderstanding

 Hi, I am very new to Scala programming and I am attempting to understand how to write a simple square function. I have: def square(x : Int) = x*x If I do: def square[T <: Number](x : T):T = x*x Then I get: error: value * is not a member of type parameter T Someone very helpful on stackoverflow stated that I should do the following: def square[T: Numeric](x: T): T = implicitly[Numeric[T]].times(x,x) This certainly works, however, when I do the following: var x = List[Int](1,2,3) x.map(square) I get: error: could not find implicit value for evidence parameter of type Numeric[T]        x.map(square) This works: x.map(square[Int]) However, it would be nice to not have to do that. Or at least understand a bit better whether or not my definition of square could be changed to avoid that. Thanks very much in advance, jim
Open this post in threaded view
|
Report Content as Inappropriate

## Re: Type polymorphism misunderstanding

 For those interested, the stackoverflow question is here: http://stackoverflow.com/questions/4056452/type-polymorphism-in-scalaI responded to James' question there to avoid cross-posting. On 10/29/2010 05:01 PM, James Bullard wrote: > Hi, I am very new to Scala programming and I am attempting to understand > how to write a simple square function. [snip] anovstrup.vcf (410 bytes) Download Attachment
Open this post in threaded view
|
Report Content as Inappropriate

## Re: Type polymorphism misunderstanding

 Ok, I guess that was premature.  My solution doesn't actually work... On 10/29/2010 05:29 PM, Aaron Novstrup wrote: > For those interested, the stackoverflow question is here: > http://stackoverflow.com/questions/4056452/type-polymorphism-in-scala> > I responded to James' question there to avoid cross-posting. > > On 10/29/2010 05:01 PM, James Bullard wrote: >> Hi, I am very new to Scala programming and I am attempting to understand >> how to write a simple square function. [snip] anovstrup.vcf (410 bytes) Download Attachment