Skip to content

Commit e3264ad

Browse files
committed
Add Higher-Kinded Types section to Scala 2 Tour
1 parent c2d85de commit e3264ad

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

_overviews/higher-kinded-types.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
layout: multipage-overview
3+
title: Advanced Type Features
4+
partof: scaladoc
5+
overview-name: Scaladoc
6+
num: 4
7+
permalink: /overviews/scaladoc/advanced-type-features.html
8+
---
9+
10+
# Advanced Type Features in Scala
11+
12+
This section introduces some advanced type system features in Scala, including **Higher-Kinded Types (HKT)**, type bounds, and type projections.
13+
14+
## Higher-Kinded Types
15+
16+
Higher-Kinded Types allow abstracting over type constructors. For example:
17+
18+
```scala
19+
trait Functor[F[_]] {
20+
def map[A, B](fa: F[A])(f: A => B): F[B]
21+
}
22+
```
23+
24+
Here `F[_]` is a type constructor that takes a single type parameter.
25+
26+
### Example Usage:
27+
28+
```scala
29+
val optionFunctor = new Functor[Option] {
30+
def map[A, B](fa: Option[A])(f: A => B): Option[B] = fa.map(f)
31+
}
32+
33+
val result = optionFunctor.map(Some(2))(_ * 2) // Some(4)
34+
```
35+
36+
## Type Bounds
37+
38+
Scala supports upper and lower bounds:
39+
40+
```scala
41+
def max[T <: Ordered[T]](x: T, y: T): T = if (x > y) x else y
42+
```
43+
44+
Here `T <: Ordered[T]` means `T` must implement `Ordered`.
45+
46+
## Type Projections
47+
48+
You can refer to a type member of another type:
49+
50+
```scala
51+
class Outer {
52+
class Inner
53+
}
54+
55+
val o = new Outer
56+
val i: o.Inner = new o.Inner
57+
```
58+
59+
## Summary
60+
61+
These features allow Scala developers to write highly abstract and reusable code. Higher-Kinded Types, type bounds, and type projections are cornerstones of Scala’s expressive type system.

0 commit comments

Comments
 (0)