简体   繁体   English

带泛型的返回类型

[英]Return type with generic with bounds

I have the following code 我有以下代码

import scala.concurrent.Future

class RequestType
class Read extends RequestType
class Write extends RequestType

object Main {
  def main(args: Array[String]): Unit = {
  }

  def dbrequest[T <: RequestType](t: T): Future[T] = {
    val dBRequest = new DBRequest
    t match {
      case r: Read => dBRequest.read(r)
      case w: Write => dBRequest.write(w)
   }
  }
}

class DBRequest {
  def read(r: Read): Future[Read] = {
    Future(r)
  }

  def write(w: Write): Future[Write] = {
   Future(w)
  }
}

read and write method return a Future of type RequestType. 读写方法返回RequestType类型的Future If T is bounded and Future is covariant, then why is the compiler failing to conform type of Future[Read] or Future[Write] to Future[T] 如果T是有界的,而Future是协变的,那么为什么编译器无法使Future[Read]Future[Write]Future[T]

Your code will compile with one small change. 您的代码将进行一个小的更改。

def dbrequest[T <: RequestType](t: T): Future[RequestType] = {

So why is it that returning Future[RequestType] works and returning Future[T] doesn't, especially since T is bounded the way it is? 那么,为什么返回Future[RequestType]起作用而返回Future[T]却不起作用,尤其是因为T受其方式的约束呢?

Think of it this way: T is resolved at compile time. 这样想: T在编译时解析。 With every invocation of dbrequest() the compiler turns T into either Read or Write . 每次调用dbrequest() ,编译器都会将T转换 ReadWrite The match statement, on the other hand, is resolved at run time. 另一方面, match语句在运行时解析。 So from the compiler's perspective the match statement returns both Read and Write . 因此,从编译器的角度来看, match的语句返回两个 ReadWrite

As has been pointed out, you don't really need a type parameter in this code, as presented. 如前所述,在此代码中,您实际上并不需要类型参数。 The following simplification is equivalent. 以下简化是等效的。

def dbrequest(t: RequestType): Future[RequestType] = {

If T is bounded and Future is covariant, then why is the compiler failing to conform type of Future[Read] or Future[Write] to Future[T] 如果T是有界的,而Future是协变的,那么为什么编译器无法使Future [Read]或Future [Write]的类型与Future [T]相一致

Your code would make sense if T was guaranteed to be Read or Write . 如果保证TReadWrite那么您的代码将很有意义。 But it could Read with SomeTrait . 但是它可以Read with SomeTrait Or a singleton type (so even making RequestType , Read and Write sealed wouldn't help). 单例类型 (因此即使将RequestTypeReadWrite密封也无济于事)。 Etc. See my answer to Returning subclass of parameterized type in Scala for a solution (just replace Output in that question with Future ). 等等,请参阅我对Scala中返回参数化类型的子类的回答以获取解决方案(只需用Future替换该问题中的Output )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM