형식 매개 변수의 하위 유형 인 특성이나 믹스 인을 가진 제네릭 클래스를 만드는 방법, 그리고 유사한 특성을 가지고 있나요 그리고 현재이처럼 사용하고 있습니다 : 이러한 클래스를 만들 수있는 일반적인 방법이있을 것 같은가 나는 다른 종류의 추가 데이터를 첨부하려고
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
이 거기를 이것을 달성하는 방법? 그런 다음
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
}
당신은 예를 들어, 할 수 있습니다
난 당신이 중요한 요구 사항을 생략하는 것으로 추측하고있다을 사용하는 것입니다. 이 인스턴스를 외부 라이브러리에 전달하고 다시 가져 와서 'ExtraData'와'getExtraData'에 캐스팅 할 수 있도록'ExternalType1'을 확장하려고합니까? 그렇지 않다면 반드시 하위 클래스 화에서 벗어나야합니다. – drstevens
예, 저는 이와 비슷한 것을하려고 합니다만, 커스텀 시리얼 라이저를 사용하는 Kryo에게하십시오. –