- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试将额外数据附加到其他类型,并且具有类似于以下的特征:
trait ExtraData {
def getExtraData() : Array[Byte]
}
我目前是这样使用它的:
class ExternalType1WithExtraData(superType:ExternalType1, bytes:Array[Byte]) extends ExternalType1(superType.a,superType.b, ...) with ExtraData {
def getExtraData() : Array[Byte] = bytes
}
class ExternalType2WithExtraData(superType:ExternalType2, bytes:Array[Byte]) extends ExternalType2(superType.z,superType.w, ...) with ExtraData {
def getExtraData() : Array[Byte] = bytes
}
似乎有一种通用的方法来创建这些类,但我还没有找到它。
--- 开始编辑 -- 添加所需的行为
给定一个函数
def sendData(ex : ExternalType1)
我希望能够将我的增强类型传递给该函数。
val data:ExternalType1 = ???
val moredata:ExternalType1 = { new ExternalType1 with ExtraData{...} }
sendData(moredata)
--- 结束编辑
我尝试按照这些思路做事,但没有成功:
// Compiler wont let me extend T
class WithExtraData[T](bytes:Array[Byte]) extends T with ExtraData{
def getExtraData() : Array[Byte] = bytes
}
:12: error: class type required but T found class WithExtraDataT extends T with ExtraData{ ^ :12: error: illegal inheritance; supertype T is not a subclass of the superclass Object of the mixin trait ExtraData class WithExtraDataT extends T with ExtraData{
// Seems closer, but doesn't work.
class WithExtraData[T](t:T, bytes:Array[Byte]) extends ExtraData {
this : T => t
def getExtraData() : Array[Byte] = bytes
}
:13: warning: a pure expression does nothing in statement position; multiline expressions may require enclosing parentheses self : T => t ^ defined class WithExtraData
scala> new WithExtraData[String]("hi", new ArrayByte) :13: error: class WithExtraData cannot be instantiated because it does not conform to its self-type WithExtraData[String] with String
有什么办法可以实现吗?
最佳答案
我认为您可以合理地获得的最接近的(至少没有宏)不是扩展 ExternalType1
,而是进行隐式转换:
class WithExtraData[T](val value: T, bytes: Array[Byte]) extends ExtraData {
def getExtraData(): Array[Byte] = bytes
}
object WithExtraData {
implicit def getValue[T](x: WithExtraData[T]): T = x.value
}
然后你可以,例如每当需要 ExternalType1
时传递 WithExtraData[ExternalType1]
。
关于scala - 有没有办法创建一个具有作为类型参数子类型的特征或混合的泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43792555/
我是一名优秀的程序员,十分优秀!