0
votes

So I have this simple Scala trait with a method that requires a type parameter specified.

The DAO class extends the trait and uses the trait's method. Even if I do not provide a concrete type to the method, the code still compiles, and I suppose this is achieved by Scala auto inferring the generic type (guessing what the type value should be)? Is it right?

And also how does Scala infer types in situations like this in general?

Thanks a lot!!

class DAO @Inject()(val configProvider: DatabaseConfigProvider) extends 
    ManagementAppDatabase {
    private val users = TableQuery[UserTable]

  def findUserByEmail(email: String): Future[Option[User]] = {
    execute(users.filter(_.email === email).result.headOption)
  }
}

trait ManagementAppDatabase {
  val configProvider: DatabaseConfigProvider
 def execute[T](dBIO:DBIO[T]): Future[T] = configProvider.get[JdbcProfile].db.run(dBIO)
}
1

1 Answers

0
votes

It's not a guess, the compiler can infer the type in this case as the object passed to the method has the type defined:

 def execute[T](dBIO:DBIO[T]): Future[T] = configProvider.get[JdbcProfile].db.run(dBIO)

So if you pass a type DBIO[Int], the compiler can fill in the rest:

 def execute[Int](dBIO:DBIO[Int]): Future[Int] = configProvider.get[JdbcProfile].db.run(dBIO)