dimanche 13 septembre 2015

Function does not check type signature

I have a map which contains functions for converting HtmlRow class into a different class. The map allows for picking the right function for the job.

I have a function typeChecked whose only job is to provide type safety at compile time. But it's not doing it's job. Below is a snippet which should not compile, but does.

The line typeChecked(typeTag[QuartileDataRow], htmlRowToNonReportableDataRow _) should cause the code not to compile, since htmlRowToNonReportableDataRow does not return a QuartileDataRow

/** Row function type */
private type RFT[T] = ( HtmlRow ) => Option[T]
private def rowConversionFunction[T](sectionSchema: SectionSchema[T], 
                                     rows: Iterable[HtmlRow]):
Iterable[T] = {
  val rowConverterMap = Map(
    typeChecked(typeTag[ReportableDataRow], htmlRowToReportableDataRow _ ),
    typeChecked(typeTag[NonReportableDataRow], htmlRowToNonReportableDataRow _),
    typeChecked(typeTag[QuartileDataRow], htmlRowToNonReportableDataRow _),
    typeChecked(typeTag[WholeOnlyDataRow], htmlRowToSingleValueDataRow _))
  val function: Option[RFT[T]] =
    rowConverterMap find { _._1.tpe =:= sectionSchema._type.tpe } map { _._2.asInstanceOf[RFT[T]] }
  function map { f => rows flatMap ( r => f(r) ) } getOrElse Iterable()
}
/** The only purpose is to have compile time type checking */
private def typeChecked[Com](tag: TypeTag[Com], function: RFT[Com]): (TypeTag[Com], RFT[Com]) =
  tag -> function





Aucun commentaire:

Enregistrer un commentaire