I want to write a function that behaves differently depending on its type parameter.
A simple example of what I want is shown below:
def f[Int] = "I'm an int"
def f[Float] = "I'm a float"
def f[Burger] = "You want fries with that?"
Is this possible in Scala or do I need some kind of work around?
Not directly; the usual way you’d do this in Scala is with a typeclass.
It’s a fair bit more verbose, but it has some advantages too — the implicit instances can be computed (using
implicit defs instead ofvals), and there can be more than one instance for any given type, which lets you select behavior at by having different instances in scope at different points of the code.The reason you can’t do it the C++ way is that Scala generics do not involve code generation for the different type-parameters (
@specializedaside, since it doesn’t do what you want either). So it doesn’t make sense to say “hey compiler, when you see an Int in that position, instead of generating the code you would from the generic template, use this specific code instead”.