Generics Contravariance in Scala PRO

When using generics Scala doesn’t support covariance. The following code doesn’t compile. object HelloSample { def main(args:Array[String]):Unit = { val a:MyStack[SportCar] = new MyStack[SportCar]; val b:MyStack[Car] = a; } } class Car class SportCar extends Car class MyStack[T] The following video clip shows the compilation error we get while trying to compile this code and […]

Type Bounds in Scala PRO

When we define a function or a class and we choose to use generics we can set limits on the unknown type: S <: T – means that S is a sub type of T S >: T – means that S is a super type of T It is also possible to mix between […]

Functions and Anonymous Classes in Scala PRO

When calling a function we indirectly invoke the apply method on the object that represents the function. We can use the anonymous inner class syntax for defining a new anonymous inner class that extends the Function relevant trait in order to create a new function. The following code sample shows that. object HelloSample { def […]

Functions as Objects in Scala PRO

Function values are treated as objects. The function A=>B is an abbreviation for using a new object instantiated from a class that extends the scala.Function1[A,B] trait and overrides the apply function. There are currently Function1, Function2, Function3… etc… up to Function22, that takes 22 parameters. The following code sample shows that. object HelloSample { def main(args:Array[String]):Unit […]

Anonymous Inner Class in Scala PRO

Scala allows us to define anonymous inner classes. The syntax is very similar to the one we know in Java. object Demo { def main(args:Array[String]):Unit = { val ob = new MyStack[Int](0) { def data:Nothing = throw new Exception(“empty stack”); } } } abstract class MyStack[T](size:Int) { def data:T; } The following video clip overviews […]

The Nothing Type in Scala PRO

The main usage for Nothing is when specifying the return type for methods which never return normally (e.g. throw an exception when been called). object Sample { def main(args:Array[String]):Unit = { val ob = getMyStack[Int](10) } def getMyStack[T](num:Int) = { new EmptyMyStack[T] } } abstract class MyStack[T](size:Int) { def data:T; } class EmptyMyStack[T] extends MyStack[T](0) […]

Generic Functions in Scala PRO

The Scala programming language allows us to define generic functions. This code sample shows that. object Sample { def main(args:Array[String]):Unit = { val ob = getMyStack[Int](10) } def getMyStack[T](num:Int) = { new MyStack[T](num) } } class MyStack[T](size:Int) { //… } The following video clips overviews this code sample, shows its execution and provides more information.

Skip to content Update cookies preferences