Skip to content

Commit b86a56a

Browse files
authored
Add code tabs for _tour/variances (#2548)
1 parent e8ef689 commit b86a56a

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

_tour/upper-type-bounds.md

+38
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ redirect_from: "/tutorials/tour/upper-type-bounds.html"
1313
In Scala, [type parameters](generic-classes.html) and [abstract type members](abstract-type-members.html) may be constrained by a type bound. Such type bounds limit the concrete values of the type variables and possibly reveal more information about the members of such types. An _upper type bound_ `T <: A` declares that type variable `T` refers to a subtype of type `A`.
1414
Here is an example that demonstrates upper type bound for a type parameter of class `PetContainer`:
1515

16+
{% tabs upper-type-bounds class=tabs-scala-version %}
17+
{% tab 'Scala 2' for=upper-type-bounds %}
1618
```scala mdoc
1719
abstract class Animal {
1820
def name: String
@@ -39,11 +41,47 @@ class PetContainer[P <: Pet](p: P) {
3941
val dogContainer = new PetContainer[Dog](new Dog)
4042
val catContainer = new PetContainer[Cat](new Cat)
4143
```
44+
{% endtab %}
45+
{% tab 'Scala 3' for=upper-type-bounds %}
46+
```scala
47+
abstract class Animal:
48+
def name: String
4249

50+
abstract class Pet extends Animal
51+
52+
class Cat extends Pet:
53+
override def name: String = "Cat"
54+
55+
class Dog extends Pet:
56+
override def name: String = "Dog"
57+
58+
class Lion extends Animal:
59+
override def name: String = "Lion"
60+
61+
class PetContainer[P <: Pet](p: P):
62+
def pet: P = p
63+
64+
val dogContainer = PetContainer[Dog](Dog())
65+
val catContainer = PetContainer[Cat](Cat())
66+
```
67+
{% endtab %}
68+
{% endtabs %}
69+
70+
{% tabs upper-type-bounds_error class=tabs-scala-version %}
71+
{% tab 'Scala 2' for=upper-type-bounds_error %}
4372
```scala mdoc:fail
4473
// this would not compile
4574
val lionContainer = new PetContainer[Lion](new Lion)
4675
```
76+
{% endtab %}
77+
{% tab 'Scala 3' for=upper-type-bounds_error %}
78+
```scala
79+
// this would not compile
80+
val lionContainer = PetContainer[Lion](Lion())
81+
```
82+
{% endtab %}
83+
{% endtabs %}
84+
4785
The `class PetContainer` takes a type parameter `P` which must be a subtype of `Pet`. `Dog` and `Cat` are subtypes of `Pet` so we can create a new `PetContainer[Dog]` and `PetContainer[Cat]`. However, if we tried to create a `PetContainer[Lion]`, we would get the following Error:
4886

4987
`type arguments [Lion] do not conform to class PetContainer's type parameter bounds [P <: Pet]`

0 commit comments

Comments
 (0)