Scala structural types with generics
In Scala, if you want to use structural types with a generic class, you must cast the instance to the structural type and import reflective calls.
Because we have to cast the instance to another type, it is better to define the type alias in a companion object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import ExampleTest.CanAddElement
import scala.language.reflectiveCalls
import org.scalatest.{FlatSpec, Matchers}
object ExampleTest {
type CanAddElement = {def add(s: Any): Boolean}
}
class ExampleTest extends FlatSpec with Matchers {
it should "add an element to the container" in {
def add[T](container: CanAddElement)(element: T): Unit = {
container.add(element)
}
val set = new java.util.HashSet[String]()
add(set.asInstanceOf[CanAddElement])("3")
set.contains("3") shouldEqual true
val list = new java.util.LinkedList[String]()
add(list.asInstanceOf[CanAddElement])("3")
list.contains("3") shouldEqual true
}
}
Did you enjoy reading this article?
Would you like to learn more about leveraging AI to drive growth and innovation, software craft in data engineering, and MLOps?
Subscribe to the newsletter or add this blog to your RSS reader (does anyone still use them?) to get a notification when I publish a new essay!
You may also like

Bartosz Mikulski
- MLOps engineer by day
- AI and data engineering consultant by night
- Python and data engineering trainer
- Conference speaker
- Contributed a chapter to the book "97 Things Every Data Engineer Should Know"
- Twitter: @mikulskibartosz
- Mastodon: @mikulskibartosz@mathstodon.xyz