Skip to content

Instantly share code, notes, and snippets.

@andypetrella
Created February 2, 2013 16:27
Show Gist options
  • Save andypetrella/4698116 to your computer and use it in GitHub Desktop.
Save andypetrella/4698116 to your computer and use it in GitHub Desktop.
Co&ContraVariance in Scala (and not Java)
> run-main Covariant
[info] Running Covariant
55.0
[success] Total time: 0 s, completed Feb 2, 2013 6:13:40 PM
>
object Covariant extends App {
trait Vehicle {
def name:String
def velocity:Float
}
case class Car(name:String, velocity:Float) extends Vehicle
object VehiculeStats {
def meanVelocity(vs:List[Vehicle]):Float =
vs match {
case Nil => 0
case vs => vs.map{_.velocity}.sum / vs.size
}
}
val christine = Car("Christine", 55f)
val cars = List(christine)
val m = VehiculeStats.meanVelocity(cars)
println(m)
}
[info] Compiling 1 Scala source and 1 Java source to /home/noootsab/src/test/target/scala-2.10/classes...
[error] /home/noootsab/src/test/Test.java:41: meanVelocity(java.util.List<Test.Vehicle>) in Test.VehiculeStats cannot be applied to (java.util.List<Test.Car>)
[error] Float mv = VehiculeStats.meanVelocity(cars);
[error] ^
[error] 1 error
[error] (compile:compile) javac returned nonzero exit code
[error] Total time: 1 s, completed Feb 2, 2013 5:25:28 PM
>
object OptionCov extends App {
import Covariant._
val christine = Car("Christine", 55f)
val someCar:Option[Car] = Some(christine)
val someVehicle:Option[Vehicle] = someCar
println(someVehicle) //prints Some(Christine)
}
import java.util.*;
public class Test {
static public abstract class Vehicle {
public String name;
public Float velocity;
public String toString() {
return this.name;
}
}
static public class Car extends Vehicle {
public Car(String name, Float velocity) {
this.name = name;
this.velocity = velocity;
}
}
static class VehiculeStats {
public static Float meanVelocity(List<Vehicle> vs) {
if (vs.isEmpty()) {
return 0f;
} else {
Float acc = 0f;
for (Vehicle v : vs) {
acc += v.velocity;
}
return acc / vs.size();
}
}
}
public static void main(String[] args) {
Car christine = new Car("Christine", 55f);
List<Car> cars = Arrays.asList(christine);
Float mv = VehiculeStats.meanVelocity(cars);
System.out.println("Mean Velocity : " + mv);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment