title: Emulating function overload in Scala
body: <p>I am rather new to Scala programming, so still figuring out canonical ways to doing something.  Lately, I wanted to write a function <code>foo</code> that would only accept a set of types for its only parameter.  Think of something like</p>
  
  <pre><code>def foo(x: [Int, String]) = ???
  </code></pre>
  
  <p>But I couldn't find anything close to the syntax above (which I find most natural to me).  Using type <code>Any</code> would loose the compile-side checking and would make it easier for problems to escape into the runtime land.</p>
  
  <p>The best I was able to come up with is something like this:</p>
  
  <pre><code>sealed abstract class Base
  case class TypeInt(v: Int) extends Base
  case class TypeString(v: String) extends Base
  
  implicit def toTypeInt(v: Int) = TypeInt(v)
  implicit def toTypeString(v: String) = TypeString(v)
  
  def foo(x: Base) = x match {
    case TypeInt(v) =&gt; println("Int: ", v)
    case TypeString(v) =&gt; println("String: ", v)
  }
  
  foo(1)
  foo("hello")
  </code></pre>
  
  <p>(As a side note, I would like to be able to just write <code>implicit case class ...</code> to avoid creating manually the <code>toType*</code> functions but that doesn't compile.)</p>
  
  <p>Is there a simpler way to write a function that accepts a parameter of a set of types in a typesafe manner?</p>
  
  <p><strong>UPDATE</strong>: It actually turns out that in my specific case I could just have used method overloading.  For some reason it's not possible to use method overloading at all in Scala worksheet which made me think that Scala doesn't have overloading at all.  But I was wrong - in regular Scala source it should be possible to use that.  There are still some shortcomings of overload usage that are described in the article on Magnet pattern that was mentioned in comments below (e.g. there is no way to overload on type Foo[Type1] and Foo[Type2] because of type erasure in JVM generics.</p>