Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

What is the difference between these two function declarations?

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

def fn(a: A): Unit = ()
like image 869
three-cups Avatar asked Feb 22 '26 08:02

three-cups


1 Answers

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)
}
like image 79
Yuriy Avatar answered Feb 25 '26 11:02

Yuriy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!