CodeMonkey CodeMonkey - 6 months ago 38
Scala Question

Is there a reason to use subtype as type parameter in Scala?

I was wondering whether there is a good reason to use subtype as functions type parameter?
Lets consider the following example:

scala> trait Animal { def sound: String }
defined trait Animal

scala> def f1[T <: Animal](a: T) = a.sound
f1: [T <: Animal](a: T)String

scala> def f2(a: Animal) = a.sound
f2: (a: Animal)String

Has f1 some advantages over f2?


I believe there are no advantages in your example. Type parameters are usually used to connect different parts of the code, but information about T is effectively lost as it doesn't match anything. Consider another example:

def f1[T <: Animal](a: T) = (a.sound, a)

def f2(a: Animal) = (a.sound, a)

Now things are different as T is passed to a return type:

class Dog extends Animal { def sound = "bow-wow" }

f1(new Dog)
//> (String, Dog) = (bow-wow,Dog@141851fd)

f2(new Dog)
//> (String, Animal) = (bow-wow,Dog@5a1fe991)

In this case you can think of f1 as of a template which is "instantiated" at compile time and effectively generates a specific method based on compile-time parameter types. So if you want to use f1(new Dog) where (String, Dog) is required it will compile, while f2(new Dog) won't.