[英]Scala method Inferred generic type
So I have this simple Scala trait with a method that requires a type parameter specified. 所以我有一个简单的Scala特征,其方法需要指定类型参数。
The DAO class extends the trait and uses the trait's method. DAO类扩展了特征并使用特征的方法。 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)? 即使我没有为该方法提供具体类型,代码仍然可以编译,并且我想这是通过Scala自动推断通用类型(猜测类型值应该是什么)来实现的? Is it right? 这样对吗?
And also how does Scala infer types in situations like this in general? 而且,在这种情况下,Scala如何推断类型?
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)
}
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: 因此,如果您传递类型DBIO[Int]
,则编译器可以填写其余部分:
def execute[Int](dBIO:DBIO[Int]): Future[Int] = configProvider.get[JdbcProfile].db.run(dBIO)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.