Melvic Ybanez
Melvic Ybanez

Reputation: 2023

How to abstract over bounded type parameters in Scala?

Say I am working on a project that has A <: Foo with Bar[A] with Baz[A] in every function definition, like the following:

def listSomething[A <: Foo with Bar[A] with Baz[A]](query: String): List[A] = ???

def readSomething[A <: Foo with Bar[A] with Baz[A]](id: Long): Option[A]

Is it possible to remove this duplication? I tried to define a type alias but it didn't seem to work. The only working thing I could come up with was to treat them as abstract type members, but then I would have to turn functions into traits, and maybe there's a better way.

Upvotes: 0

Views: 46

Answers (1)

yǝsʞǝla
yǝsʞǝla

Reputation: 16412

trait Foo
trait Bar[A]
trait Baz[A]
trait All[A] extends Foo with Bar[A] with Baz[A]
def listSomething[S <: All[S]](query: String): List[S] = ???

Upvotes: 1

Related Questions