Reputation: 3392
I need to do the following transformation and columnNames
should be Seq[String]
, however it is always Seq[Any]
.
How can I solve this task?
val cols = Seq("col1","col2")
val columnNames: Seq[String] = cols ++ "col3"
Upvotes: 1
Views: 3428
Reputation: 1099
++
is the binary operator(method) on two collections. But the :+
or +:
is the operator to add an element
to the collection
( the collection
should always be adjacent to :
and the element
to be added to the collection should always be adjacent to +
in :+
ie., it should be used as collection :+ element
or element +: collection
to append
or prepend
the element
to the collection
respectively.So, the cols :+"col3"
will give us the expected answer, because then the "col3"
will be treated as a string element
to be added to cols
collection
.
While using, cols ++ "col3"
, the String
"col3"
is being treated by the compiler as a collection ie.,as List('c','o','l','3')
, cols
is a collection of strings. Hence the resulting collection is List[Any]
, because it contains strings and chars, the super-type of String
and Char
is inferred to be Any
by the compiler.
Upvotes: 1
Reputation: 1162
It should be :
val columnNames: Seq[String] = cols :+ "col3"
:+
is a method on whatever type is returned by someVariable.next().
You are getting Class Any
is the root of the Scala class hierarchy. Every class in a Scala execution environment inherits directly or indirectly from this class.
Upvotes: 0
Reputation: 27373
you should do :
val columnNames: Seq[String] = cols :+ "col3"
or
val columnNames: Seq[String] = cols ++ Seq("col3")
In your case the result is Seq[Any]
because Any
is the common supertype of String
and Char
Upvotes: 2