three-cups three-cups - 1 year ago 99
Scala Question

What is the difference between a generic function and polymorphic argument types in scala?

What is the difference between these two function declarations?

def fn[T <: A](t: T): Unit = ()

def fn(a: A): Unit = ()

Answer Source

This is 2 subtypes of Universal polymorphism: Parametric & Inclusion (inheritance/subtyping). They have own pros & cons, but for this particular case difference, what I can imagine, that for type polymorphism you will miss possibilities to overload functions (what is valuable part of inclusion polymorphism).

For example:

class A
class B // extends A // - if it is needed

class Foo {
  def fn(t: A): Unit = ()
  def fn(t: B): Unit = () // - is OK

class Boo {
  def fn[T <: A](t: T): Unit = ()
  def fn[T <: B](t: T): Unit = () // - is not OK (func names conflict)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download