Scala types: Class A is not equal to the T where T is: type T = A

前端 未结 3 709
一生所求
一生所求 2021-01-19 05:13

I was reading the section 20.7 of the book Programming in Scala and I was wondering why while this code compiles:

class Food
class Fish extends Food
class Gr         


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-19 05:56

    Regarding the second part of your question: it doesn't. Animal doesn't specify that its food is Food, but some subtype of Food. Would the compiler accept this, code like your example would compile, and wrongly so. The compiler doesn't know that the necessary subtype is Grass (which is why eat(new Grass) doesn't work either), it just knows that there are some foods your cow can't eat and is cautious about it.

提交回复
热议问题