vendredi 28 septembre 2018

Pass Type Parameter scala

Hi I'm not understanding something about passing Type parameters or reflection but basically I'm trying to pass a type from one object to another. One object can have a type and then pass it to another method. I think this can be done with ClassTags but I'm getting a little confused somewhere. The class is like this

case class SumAggregation(override val aggColumn: String)
    extends Aggregation[Long]("sum", aggColumn: String) {

  override type initType = Long
  def initializationValue: Long = 0L
  def stringToType(str: String) = str.toLong

}

And in the application class there is a call like so

val nVS = deserialise[typeL](true)(newValue)(v => v.toLong)

Where deserialize method has the following definition

def deserialise[T](isInit: Boolean)(bytes: Array[Byte])(cbf: String => T ):  T = {
    val ois = new ObjectInputStream(new ByteArrayInputStream(bytes))
    val value = ois.readObject
    ois.close()
    if (isInit) cbf(value.asInstanceOf[String]) else value.asInstanceOf[T]
  }

And I was hoping to get the typeL completely dynamically from the initType field of an instance of SumAggregation with something like this type typeL = mySumAgg.initType.

I know passing the type like that won't work but does anyone know exactly the right approach with ClassTags (or TypeTags if that works better) and maybe a code sample that would help?





Aucun commentaire:

Enregistrer un commentaire