Scala incorrect type inference Intellij


A piece of code that I have refactored out of my main method to a separate method is having an issue with type inference when iterated over.

val resourceId = resourceIdjsonobject.get("resourceId").toString
val sensorJson = resourceIdjsonobject.get("stat-list").asInstanceOf[JSONObject].get("stat").asInstanceOf[JSONArray]
val list = new ListBuffer[Tuple2[JSONObject, String]]()

for (y <- sensorJson) {


This is the code that I have specified within my main method and a separate method. Using Ctrl-Q I have found that sensorJson and all variables aside from y are correctly inferred, y is being inferred as Any which is incorrect as within the main method it is inferred as JSONObject.

This is the error I get on compilation:

value foreach is not a member of net.minidev.json.JSONArray

I have tried using y:JSONObject to specify the type of y though I then get the error on compilation:

value filter is not a member of net.minidev.json.JSONArray

Where am I going wrong?


This appears to be a Java library. As far as I can see JSONArray is a java.util.List[Object] so how y could ever be JsonObject is a mystery to me. However I’m pretty sure you imported some conversion java.util.List[A] => mutable.Seq[A] in your main method. Take a look at$.html


Managed to find the issue, found this within the main method which resolved the issue:

implicit def JSONArray2List(x: JSONArray): ListBuffer[JSONObject] = {
  var list = new ListBuffer[JSONObject]()
  for (y <- 0 until x.size()) {

I’ve mimicked this within the refactored method by using a similar way to append to list.