为什么我不能将特征传递给 Scala 函数并调用它:response[A: T](r: A) = { r(value) }
Why can't I pass a trait to a Scala function and call it: response[A: T](r: A) = { r(value) }
我正在尝试实现一个通用的 response
函数,它接受一个 Int
和一个对象,然后在提供的对象上调用 apply(e: Int)
(这将 return一个新实例)。这是我目前所拥有的:
trait GPResponse {
abstract def apply(error: Int)
}
trait GPResponseMapping {
def response[A: GPResponse](error: Int, instance: A) = { (resultCodeFor(error), instance(error)) } // Make a tuple of code and GPResponse instance
...
生成这些编译器错误:
[error] GPResponseMapping.scala:68: utility.GPResponse does not take type parameters
[error] def response[A: GPResponse](error: Int, instance: A) = { (resultCodeFor(error), instance(error)) }
[error] ^
[error] GPResponseMapping.scala:68: A does not take parameters
[error] def response[A: GPResponse](error: Int, instance: A) = { (resultCodeFor(error), instance(error)) }
[error] ^
我想做的是根据错误代码和响应对象实例的组合创建元组。响应对象将错误代码作为构造函数参数(apply()
参数)和 return 实例。
当你这样写的时候:
def response[A: GPResponse](error: Int, instance: A) = {
编译器将其扩展为:
def response[A](error: Int, instance: A)(implicit $ev0 GPResponse[A]) = {
但是,由于您这样定义 GPResponse
:
trait GPResponse {
它没有类型参数,所以你不能写成A : GPResponse
。
啊……好吧,明白了。显然我必须直接调用 apply()
方法,如 instance.apply(...)
中那样,这有点令人吃惊,但它有效:
trait GPResponse {
abstract def apply(error: GPError): GPResponse
}
trait GPResponseMapping {
def response(error: Int, instance: GPResponse) = { (resultCodeFor(error), instance.apply(error)) }
...
如果有人能解释为什么我不能在这种情况下使用 instance(error)
,我将不胜感激。谢谢!
我正在尝试实现一个通用的 response
函数,它接受一个 Int
和一个对象,然后在提供的对象上调用 apply(e: Int)
(这将 return一个新实例)。这是我目前所拥有的:
trait GPResponse {
abstract def apply(error: Int)
}
trait GPResponseMapping {
def response[A: GPResponse](error: Int, instance: A) = { (resultCodeFor(error), instance(error)) } // Make a tuple of code and GPResponse instance
...
生成这些编译器错误:
[error] GPResponseMapping.scala:68: utility.GPResponse does not take type parameters
[error] def response[A: GPResponse](error: Int, instance: A) = { (resultCodeFor(error), instance(error)) }
[error] ^
[error] GPResponseMapping.scala:68: A does not take parameters
[error] def response[A: GPResponse](error: Int, instance: A) = { (resultCodeFor(error), instance(error)) }
[error] ^
我想做的是根据错误代码和响应对象实例的组合创建元组。响应对象将错误代码作为构造函数参数(apply()
参数)和 return 实例。
当你这样写的时候:
def response[A: GPResponse](error: Int, instance: A) = {
编译器将其扩展为:
def response[A](error: Int, instance: A)(implicit $ev0 GPResponse[A]) = {
但是,由于您这样定义 GPResponse
:
trait GPResponse {
它没有类型参数,所以你不能写成A : GPResponse
。
啊……好吧,明白了。显然我必须直接调用 apply()
方法,如 instance.apply(...)
中那样,这有点令人吃惊,但它有效:
trait GPResponse {
abstract def apply(error: GPError): GPResponse
}
trait GPResponseMapping {
def response(error: Int, instance: GPResponse) = { (resultCodeFor(error), instance.apply(error)) }
...
如果有人能解释为什么我不能在这种情况下使用 instance(error)
,我将不胜感激。谢谢!