gpt4 book ai didi

scala - 有没有办法创建一个具有作为类型参数子类型的特征或混合的泛型类

转载 作者:行者123 更新时间:2023-12-01 10:18:52 25 4
gpt4 key购买 nike

我正在尝试将额外数据附加到其他类型,并且具有类似于以下的特征:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com