Camilo Sampedro
Camilo Sampedro

Reputation: 1436

Is there any way that a type can be saved inside a Scala list?

I was trying to create something like a FilterList with an Enumeration called FilterType.

FilterList should have a list of (filterValue, ClassOfValue, FilterType) tuples, for example

val listOfFilters: List[(String, ???, FilterType)] = List(
  ("fromDate", String, DateFilter),
  ("toDate", String, DateFilter),
  ("id", Long, IdFilter)
)

The main reason for this is to read that filter from and write that filter to JSON with something like:

(__ \ filterName).read[ClassOfValue]

The problem is that I have not found a way to replace the ??? and I don't even know if it is possible in Scala.

edit:

Intellij IDEA suggest me to specify it as an Object, but it doesn't feel like there should be a Class reference:

val listOfFilters: List[(String, Object, FilterType)] = List(
  ("fromDate", String, DateFilter),
  ("toDate", String, DateFilter),
  ("id", Long, IdFilter)
)

Upvotes: 2

Views: 63

Answers (1)

evan.oman
evan.oman

Reputation: 5572

Other than creating an enum value for each type of ClassOfValue, you could also make a Filter class which takes the ClassOfValue as a type parameter. This filter class would then handle its own JSON input/output. It would look something like this:

import scala.reflect.runtime.universe.{TypeTag, typeOf}

object FilterType extends Enumeration
{
    type FilterType = Value
    val DateFilter, IdFilter = Value
}

import FilterType._

case class Filter[A](filterValue: String, filterType: FilterType)(implicit tt: TypeTag[A])
{
    def myTypeParam: Unit = println(s"My Type Param is ${typeOf[A]}")

    def applyFilter(data: A): A = ???
}


val l: List[Filter[_]] = List(Filter[String]("fromDate", DateFilter), 
                         Filter[String]("toDate", DateFilter), Filter[Long]("id", IdFilter))

l.foreach(_.myTypeParam)

/*
    Output: 
    My Type Param is String
    My Type Param is String
    My Type Param is Long
*/

So in that applyFilter method you would have something like <LOOKUP FILTER VALUE>.read[A] and then <FILTERED DATA>.write[A].

Upvotes: 3

Related Questions