[V] 대신 Long, Double 형식 만 허용 할 수있는 일반 클래스를 작성해야합니다.
class DummyGenericClass[V](data:Seq[V])
또한 유형에 따라 구현 차이가 있습니다. 나는 뭔가를하고 싶다.
val typ = if (V is Long) "x" else "y"
그러한 코드를 작성하기 위해 스칼라에서 권장 / 모범 사례는 무엇입니까?
동일한 파일에 정의 된 구현으로 가능한 구현을 제한하는 봉인 된 특성을 사용하여이를 달성 할 수 있습니다.
sealed trait DummyGenericClass[V] {
val data: Seq[V]
val typ: String
}
class LongClass(val data: Seq[Long]) extends DummyGenericClass[Long] {
val typ = "x"
}
class DoubleClass(val data: Seq[Double]) extends DummyGenericClass[Double] {
val typ = "y"
}
DummyGenericClass
형식이 안전한 방법에 대한 제네릭 생성자를 갖고 싶다면 팩토리 패턴과 결합 된 typeclass를 사용하는 것입니다.
object DummyGenericClass {
trait Factory[T] {
def create(seq: Seq[T]): DummyGenericClass[T]
}
object Implicits {
implicit val longProvider =
new Factory[Long] {
def create(seq: Seq[Long]) = new LongClass(seq)
}
implicit val doubleProvider =
new Factory[Double] {
def create(seq: Seq[Double]) = new DoubleClass(seq)
}
}
def apply[T: Factory](seq: Seq[T]) = implicitly[Factory[T]].create(seq)
}
다음과 같은 방법으로 사용할 수 있습니다.
import DummyGenericClass.Implicits._
val foo = DummyGenericClass(Seq.empty[Long])
val bar = DummyGenericClass(Seq.empty[Double])
// Won't compile:
val baz = DummyGenericClass(Seq.empty[String])
다른 방법 DummyGenericClass
은 인스턴스 를 생성하기 위해 타입 클래스를 정의 할 필요가 없으며 , 팩토리 메서드에서 ClassTag
바인딩을 전달 T
하는 것입니다. 그러나이 솔루션은 지원되지 않고 런타임에 실패 할 유형 인수를 전달할 수 있으므로 유형 안전 방법이 아니므로 권장되지 않습니다.
이 생성자를 사용하는 제네릭 메서드를 원하면 DummyGenericClass.Factory
해당 메서드에 바인딩 된 컨텍스트도 추가해야합니다 .
def add[T: DummyGenericClass.Factory]
(a: DummyGenericClass[T], b: DummyGenericClass[T]) =
DummyGenericClass(a.data ++ b.data)
import DummyGenericClass.Implicits._
add(DummyGenericClass(Seq(1.0)), DummyGenericClass(Seq(2.0)))
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다