I would like to define a function that applies * 2 to its argument, which works for all types where it makes sense. I tried using structural types:
import scala.language.reflectiveCalls def double[T](x: Any{def * (arg0: Int): T}) = x * 2
It works for strings:
scala> double("a") res85: String = aa
But not for numbers:
scala> double(4) java.lang.NoSuchMethodException: java.lang.Integer.$times(int) at java.lang.Class.getMethod(Class.java:1778) at .reflMethod$Method1(<console>:18) at .double(<console>:18) ... 32 elided
- Why do I need this error message?
- Is it possible to do what I want using structural types?
- Can this be done in another way?
Change By "do what I want", I mean working with already existing types, such as numbers and strings, and not just for classes that I define myself.
types scala
michau
source share