Midterm exam: Variance

m.hosseinian
Windoof-User
Windoof-User
Beiträge: 34
Registriert: 3. Mai 2015 21:28

Midterm exam: Variance

Beitrag von m.hosseinian »

Hi everyone,

Can anyone please tell me about the answers to question 1-c ?
I remember I got full points from the first part but now that I am reviewing, I faced a problem.
Maybe, my memory doesn't help!

BR,
Moe

Assax
Windoof-User
Windoof-User
Beiträge: 41
Registriert: 2. Dez 2011 10:38

Re: Midterm exam: Variance

Beitrag von Assax »

This is confusing at first but becomes rather easy once you carefully take a look at the LSP slides, specifically slide 23.
f: T1 -> T2
f': T1' -> T2'

f' <: f <=> T1 <: T1' and T2' <: T2
Where T1 and T2 can be seen as argument type and return type respectively.
Think about what the sentence
Standard subtyping relies on contra-variance of the argument types and covariance of the return types.
Now let's apply this for 1-C.

we have our function type f: (MyClass) => Boolean

which means you can assign any function that takes a MyClass and returns a Boolean into f.
But since functions in Scala can be treated as types you can also "subtype" functions.

Looking at the quote again this means that a subtype of the function that F expects requires contra-variance in MyClass and covariance in Boolean.

So basically you can put in any function that has a "bigger" argument type than MyClass, or MyClass itself, and a smaller or equal return type than boolean.

Example:

f = f2 works (Any > MyClass and Boolean = Boolean)
f = f3 Does not work because Any is not a subtype of Boolean

Hope this helped

m.hosseinian
Windoof-User
Windoof-User
Beiträge: 34
Registriert: 3. Mai 2015 21:28

Re: Midterm exam: Variance

Beitrag von m.hosseinian »

Thank you very much for your comprehensive answer.
So what are your choices among f1..f6 ?
I assume f6 is not the answer.
But, I remember I have chosen this in the exam and they have accepted.
I'm not pretty sure. That's originally why I put this question here.

Assax
Windoof-User
Windoof-User
Beiträge: 41
Registriert: 2. Dez 2011 10:38

Re: Midterm exam: Variance

Beitrag von Assax »

F1 won't work (Any > Boolean)
F2 Will work as explained
F3 Will not work, again Any > Boolean
F4 will not work because MySubclass < Myclass, remember arguments are about contravariance!
F5 will work, any > MyClass and Nothing < Boolean
F6 will not work and this is tricky. Null is a subclass of every AnyRef, but you have to know that AnyRef is only the super class of classes that are not Int , Boolean etc, they have their own Superclass AnyVal. As such Null is not a sub of Boolean and will not be accepted for F.


http://i.imgur.com/yuQAXjv.png

You can try it out, start the scala repl in your command line, define the functions f1 to f6 and replace the ??? with null.

Then define f as var f: MyClass => Boolean

and try to assign f1 to f6 to f and see what it tells you.

Antworten

Zurück zu „Archiv“