Scala方法推断通用类型 [英] Scala method Inferred generic type

查看:92
本文介绍了Scala方法推断通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个简单的Scala特征,其方法需要指定类型参数.

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

DAO类扩展了特征并使用特征的方法.即使我没有为该方法提供具体类型,代码仍然可以编译,并且我想这是通过Scala自动推断出通用类型(猜测类型值应该是什么)来实现的?是吗?

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?

在这样的情况下,Scala如何推断类型?

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

非常感谢!

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)

因此,如果您传递类型DBIO[Int],则编译器可以填写其余部分:

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)

这篇关于Scala方法推断通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆