I was trying to convert Iterable[Any]
to String
in scala
val enrichmentExpr: Iterable[Any]
// enrichmentExpr:List(List(test string1, test string2))
not able to convert using mkString
:
val newenrichmentExpr = enrichmentExpr.mkString
println(s"newenrichmentExpr:$newenrichmentExpr")
// newenrichmentExpr:List(test string1, test string2)
below is the expected output
newenrichmentExpr:test string1, test string2
Try the following
val result = enrichmentExpr
.flatMap(_.asInstanceOf[List[List[String]]])
.mkString(", ")
The problem is that the Iterable
you have is of type Any
. You can't flatten directly. First you need to cast to the type List[List[String]]
and then you would be able to flatten the collection. Once you did that, you can do the mkString
with the expected result
The code above will solve the problem you are having, but it will bring some other risks. Since your Iterable
is of type Any
, you could have any possible type of value different than a List
or some other value that can't be flattened. If that happens, you will have an error at runtime.
The compiler doesn't know how to flatten type Any inside the Iterable
. Maybe you should consider to define the variable enrichmentExpr
with another type of value.
The following text with good practices should help you
Avoid using
Any
orAnyRef
or explicit casting, unless you've got a really good reason for it. Scala is a language that derives value from its expressive type system, usage ofAny
or of typecasting represents a hole in this expressive type system and the compiler doesn't know how to help you there.