Function arguments: upper bound vs parent class as argument?

Consider that:

abstract class FlyingObject;
case class Rocket(name: String) extends FlyingObject;

what is the difference between these two function declarations:

def launch[T <: FlyingObject](fo: T)

and

def launch(fo: FlyingObject)

It would be nice to have a few examples when to use which type of declaration ...

[UPDATE]

Another great example and explanation can be found there . This is another example of when you should use an upper bound instead of a simple derived class as a parameter.

+5
source share
2 answers

It may be helpful to have a T that is more specific than a FlyingObject. Perhaps imagine you have a method

def modifyName(fo: FlyingObject, newName: String): FlyingObject = fo.copy(name=newName)

Returns a copy of the FlyingObject with the changed name. This makes this code not typecheck:

val newRocket: Rocket = modifyName(oldRocket, "new name")

modifyName FlyingObject, Rocket. :

def modifyName[T <: FlyingObject](fo: T, newName: String): T = fo.copy(name=newName)

Rocket, Rocket - , .

+7

@stew . , , , , , , . , - ( ).

, :

def collide[A <: FlyingObject, B <: FlyingObject]
  ( a: A, b: B )( implicit collider: Collider[A,B] ) = collider.apply(a,b)

Collider. :

def collide( a: FlyingObject, b: FlyingObject ) = a.collide(b)

Obect-Oriented , ( ).

+4

All Articles