Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

Matching a Scala generic where type is unknown at compile time

I have two generic classes that inherit from a abstract parent that look like this:

abstract class Sketch[S]

class CompactSketch[S] extends Sketch[S]

class UpdatableSketch[U, S <: UpdatableSummary[U]] extends Sketch[S] {
    def compact: CompactSketch[S]
}

I have a function that returns the abstract type

def heapifySketch[S](bytes: Array[Byte], deserde: SummaryDeserializer[S]): Sketch[S]

I want to find out which of the two classes has been returned and modify if necessary

def ReadCompactSketch[U, S <: UpdatableSummary[U]](bytes: Array[Byte], deserde: SummaryDeserializer[S]): CompactSketch[S] = {
    heapifySketch(bytes, deserde) match {
        case s: CompactSketch[S] => s
        case u: UpdatableSketch[U, S] => u.compact
    }
}

Matching like this yields a warning about type erasure. I've looked into TypeTags, but I can't seem to find an example where the type isn't known until runtime. What is the proper way to verify that the heapifySketch has returned the correct generic type?

question from:https://stackoverflow.com/questions/65835602/matching-a-scala-generic-where-type-is-unknown-at-compile-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...