1

I have an Object testCat having value List(123, 456, 789) and I would like to convert this Object to List[Object] in scala. When I use asInstanceOf, I got the error:

DataSource.scala:310: T0 does not take parameters
[ERROR] [Console] [error]
var testCat = eachMultiCat.asInstanceOf(List[Object])
[ERROR] [Console] [error]

Can anybody help me with this issue? Thank you very much.

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Le Kim Trang
  • 369
  • 2
  • 5
  • 17
  • 2
    Your syntax for using `asInstanceOf` is incorrect - it isn't a function taking a type as parameter, but a parameter-less function that needs a type specification. Basically, replace the parentheses "`()`" with square brackets: `.asInstanceOf[List[Object]]` – Shadowlands Oct 12 '15 at 04:32
  • Dear Shadowlands, I encountered the same issue. The object is comming from parsing JSon, anyway I already found another way to parse the list. Thank you very much. – Le Kim Trang Oct 12 '15 at 04:44

3 Answers3

3
.asInstanceOf[List[Object]]

with square brackets, as it is a type parameter.

Still wondering, why a conversion from Object to List of Objects is necessary. Smells fishy!

Martin Senne
  • 5,939
  • 6
  • 30
  • 47
0

Try this:

val obj1: Object = List(123, 456, 789)
println(obj1)

val obj2 = obj1.asInstanceOf[List[Object]]
println(obj2)

val obj3 = obj1.asInstanceOf[List[Int]]
println(obj3)

// cant do: obj1.map(_*2)
// can't do: obj2.map(_*2)

// this works
println(obj3.map(_*2))

OUTPUT:

List(123, 456, 789)
List(123, 456, 789)
List(123, 456, 789)
List(246, 912, 1578)
tuxdna
  • 8,257
  • 4
  • 43
  • 61
0

I found a way to solve my problem, this is all of working code

val multiCategoryOne =
    for { JString(x) <- (content \\ ancesstorCategories").children} yield x

var multiCategoryMany:List[Object] = Nil
if (multiCategoryOne == Nil) {
    // multiple items in cart
    val elements = (content \\ "ancesstorCategories").children
    for ( acct <- elements ) {
        val eachMultiCat = for { JString(x) <- acct} yield x
        multiCategoryMany = multiCategoryMany ::: List(eachMultiCat)
    }

} else {
    // one item in cart
    multiCategoryMany = multiCategoryMany ::: List(multiCategoryOne)
}
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Le Kim Trang
  • 369
  • 2
  • 5
  • 17