作品:
trait Transformer[A, B] {
def transform(a: A): B
}
class TransformerImpl extends Transformer[Int, String] {
override def transform(value: Int): String = {
value.toString
}
}
这就是我想要的,因为只有一个参数的特征更简单,而且B的具体值由A决定。但是,它不起作用。
trait Transformer2[A] {
def transform[B](a: A): B
}
class Transformer2Impl extends Transformer2[Int] {
override def transform[String](value: Int): String = {
value.toString
}
}
错误:
-- [E007] Type Mismatch Error: --------
3 | value.toString
| ^^^^^^^^^^^^^^
| Found: String
| Required: String
这也用不同的方法签名,不起作用:
class Transformer2IntToIntImpl extends Transformer2[Int] {
override def transform(value: Int): Int = {
value
}
}
错误:
-- Error: ----------------------------------------------------------------------
1 |class Transformer2IntToIntImpl extends Transformer2[Int] {
| ^
|class Transformer2IntToIntImpl needs to be abstract, since def transform[B](a: A): B in trait Transformer2 is not defined
|(Note that
| parameter A in def transform[B](a: A): B in trait Transformer2 does not match
| parameter Int in override def transform(value: Int): Int in class Transformer2IntToIntImpl
| )
-- [E038] Declaration Error: ---------------------------------------------------
2 | override def transform(value: Int): Int = {
| ^
|method transform has a different signature than the overridden declaration
|-----------------------------------------------------------------------------
2 errors found
根据错误,我尝试了几种替代方案,但没有成功。
这对我有用:
trait Transformer2[A] {
type B
def transform(a: A): B
}
class Transformer2Impl extends Transformer2[Int] {
type B = String
override def transform(value: Int): String = {
value.toString
}
}
class Transformer2IntToIntImpl extends Transformer2[Int] {
type B = Int
override def transform(value: Int): Int = {
value
}
}
val ans1 = new Transformer2Impl().transform(5)
val ans2 = new Transformer2IntToIntImpl().transform(5)
我还是想知道为什么原来的代码失败了。