Should Scala lower border allow same hierarchy objects?

I just started Scala and want to clear some basics. In the function below, the lower limit is set to Puppy. Why Puppy1 and Puppy2 are allowed in the code below.

class Animal
class Dog extends Animal
class Puppy extends Animal
class Puppy1 extends Animal
class Puppy2 extends Puppy

class AnimalCarer{
    def display [T >: Puppy](t: T){
    println(t)
    }
}

val animal = new Animal
val dog = new Dog
val puppy = new Puppy
val puppy1 = new Puppy1
val puppy2 = new Puppy2

val animalCarer = new AnimalCarer
animalCarer.display(animal)
animalCarer.display(puppy)
animalCarer.display(puppy1)
animalCarer.display(puppy2)
animalCarer.display(dog)
+4
source share
2 answers

Since you are not explicitly populating T, the compiler is trying to pass it to you with suitable types to make this compiler:

animalCarer.display[testing.ParamTest.Animal](ParamTest.this.puppy1);
animalCarer.display[testing.ParamTest.Puppy](ParamTest.this.puppy2);
animalCarer.display[testing.ParamTest.Animal](ParamTest.this.dog)

This is part of the Scala Local Type Inference algorithm . As you can see, each method call is displayed on the right T, for example puppy1: Animal, which adheres to a lower bound.

+1
source

Scala, ().

def foo[T >: Puppy](t: T) = t

foo(new Puppy1) //compiles

foo[Puppy1](new Puppy1) //give compilation error

Scala REPL

scala> def foo[T >: Puppy](t: T) = t
foo: [T >: Puppy](t: T)T

scala> foo(new Puppy1)
res9: Animal = Puppy1@4d49af10

scala> foo[Puppy1](new Puppy1)
<console>:16: error: type arguments [Puppy1] do not conform to method foo type parameter bounds [T >: Puppy]
       foo[Puppy1](new Puppy1)
      ^
+1

Source: https://habr.com/ru/post/1659633/


All Articles