---
title: "Scala structural types with generics"
description: "A short example of defining a structural type which matches a generic class"
author: "Bartosz Mikulski"
author_bio: "Principal AI Engineer & MLOps Architect. I bridge the gap between \"it works in a notebook\" and \"it works for 200 million users.\""
author_url: https://mikulskibartosz.name
author_linkedin: https://www.linkedin.com/in/mikulskibartosz/
author_github: https://github.com/mikulskibartosz
canonical_url: https://mikulskibartosz.name/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.

```
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
  }
}
```