0

I am new to scala and have questions on scala generics

enter image description here

Question is how animalContainer.add method is accepting new Cat. From my understanding B>:A - A is Animal and B is Cat. Cat is NOT super typs of animal . How it is working..

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Learn Hadoop
  • 2,760
  • 8
  • 28
  • 60
  • 4
    [Why not upload images of code on SO when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question/) – Dmytro Mitin Dec 04 '19 at 16:46
  • 3
    I think the reason it isn't apparent is because you haven't actually implemented your `add` method yet. When you do, you'll see the compiler will only allow you to create a new instance of the `Container[B]` for this to work, and when you create a new container, it'll be a `Container[Animal]`, not `Container[Dog]`. – Yuval Itzchakov Dec 04 '19 at 16:47
  • **B** is not inferred to be `Cat` but rather `Animal`. – Luis Miguel Mejía Suárez Dec 04 '19 at 16:48
  • Thanks for ur response. while mouse over i am getting def add[B >: Animal](element: B): Unit - i am passing new Cat to add method.. how it is possible cat>:Animal .. can you please explain in layman terms – Learn Hadoop Dec 04 '19 at 17:03
  • 1
    You need to understand that a value has many types not just one, thus `new Cat` has _(among others)_ the types **Cat**, **Animal**, **AnyRef**, **Any** etc. - So, in this case **B** needs to be inferred, for that purpose the compiler attempts to find the **LUB** between **Animal** and all the types of `new Cat`, in this case **Animal** is inferred. – Luis Miguel Mejía Suárez Dec 04 '19 at 17:54

1 Answers1

1

B is not Cat, B is Animal. The inferred type of add is then effectively:

def add(element: Animal)

You are able to pass Cat here because Cat extends Animal.

Brian McCutchon
  • 8,354
  • 3
  • 33
  • 45
  • then why we need to add [B >: A] in add method. without this line, i am getting compile time error .. – Learn Hadoop Dec 04 '19 at 17:30
  • 1
    That's a different question. See https://stackoverflow.com/questions/37334674/why-method-defined-like-consb-av-b-accepts-argument-of-type-which-is-n – Brian McCutchon Dec 04 '19 at 19:14