Search code examples
scalacollectionsnestedscala-collectionsinstanceof

Scala : How to find types of values inside a scala nested collection


consider the following variables in scala :

val nestedCollection_1 = Array(
  "key_1" -> Map("key_11" -> "value_11"),
  "key_2" -> Map("key_22" -> "value_22"))

val nestedCollection_2 = Map(
  "key_3"-> ["key_33","value_33"],
  "key_4"-> ["key_44"->"value_44"])

Following are my questions :

1) I want to read the values of the variables nestedCollection_1, nestedCollection_2 and ensure that the value of the variables are of the format

Array[Map[String, Map[String, String]]

and

Map[String, Array[String]]]

2) Is it possible to get the detailed type of a variable in scala? i.e. nestedColelction_1.SOME_METHOD should return Array[Map[String, Map[String, String]] as type of its values


Solution

  • I am not sure what exacltly do you mean. Compiler can ensure type of any variable if you just annotate the type:

    val nestedCollection_2: Map[String, List[String]] = Map(
      "key_3"-> List("key_33", "value_33"),
      "key_4"-> List("key_44", "value_44"))
    

    You can see type of variable in scala repl when you define it, or using Alt + = in Intellij Idea.

    scala> val nestedCollection_2 = Map(
         |   "key_3"-> List("key_33", "value_33"),
         |   "key_4"-> List("key_44", "value_44"))
    nestedCollection_2: scala.collection.immutable.Map[String,List[String]] = Map(key_3 -> List(key_33, value_33), key_4 -> List(key_44, value_44))
    

    Edit

    I think I get your question now. Here is how you can get type as String:

    import scala.reflect.runtime.universe._
    def typeAsString[A: TypeTag](elem: A) = {
      typeOf[A].toString
    }
    

    Test:

    scala> typeAsString(nestedCollection_2)
    res0: String = Map[String,scala.List[String]]
    scala> typeAsString(nestedCollection_1)
    res1: String = scala.Array[(String, scala.collection.immutable.Map[String,String])]