I wanted to know if there is an equivalent of the C# generic delegates in Scala.
The reference website is: http://msdn.microsoft.com/en-us/library/dd233060.aspx
I’m trying to make a complete comparison between C# and Scala, about (co)(contra)(in)variance.
1
Scala doesn’t have delegates, but you are free to assign functions/lambdas to variables. Here, normal subtyping rules apply. A function f: A => B
is a subtype of g: C => D
if the argument is a supertype A > C
(contravariance) and the return type is a subtype B < D
(contravariance). Note that any of those four types might actually be tuples, so that tuple subtyping will be applied in such cases.
Example:
// two (sub-)types to demonstrate variance
class A()
class B() extends A
var delegate: Option[B => A] = None
// a few simple lambdas that can be assigned
delegate = Some((b: B) => new A()) // invariant
delegate = Some((b: B) => new B()) // return type covariance
delegate = Some((a: A) => new A()) // argument type contravariance
delegate = Some((a: A) => new B()) // co- and contravariance
// can we assign methods to function types? Yes!
class Context(retVal: A) {
def meth(b: B): A = retVal
}
val ctx = new Context(new A())
delegate = Some(ctx.meth _) // partial application
delegate = Some(b => ctx.meth(b)) // wrapping in lambda
If we add (more) generics, this doesn’t change anything since functions already are generic types in Scala. In particular, co- and contravariance for functions is available because functions are actually defined as trait Function1[-T1, +R]
. User-defined types can also make use of variance when defined properly.