[英]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
转换为 Read
或Write
。 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
的语句返回两个 Read
和Write
。
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
. 如果保证
T
是Read
或Write
那么您的代码将很有意义。 But it could Read with SomeTrait
. 但是它可以
Read with SomeTrait
。 Or a singleton type (so even making RequestType
, Read
and Write
sealed wouldn't help). 或单例类型 (因此即使将
RequestType
, Read
和Write
密封也无济于事)。 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.