user7804781 user7804781 - 1 year ago 73
Scala Question

Initialize a list from a function return in Scala

How do you declare a list var that is initialized by the returning list of a funtion?

I want a

List[Any]
, let's call it
newList
, to be assigned to the values returned by some function, say
makeList()
, that returns a
List[Any]
.

like:

var newList = makeList(arg1, arg2)


Which gives an error: "Expression of type Any doesn't conform to expected type List[Any]"

I want to then index into the first element of newList like:
newList(0)


I have tried
val newList : List[Any] = makeList(arg1, arg2)

but I still get that error message at
newList(0)


I've confirmed that
makeList
returns a List[Any].

The last error is coming from having
newList(0)
as the last line in a function, so, the last question would be: what would the return type of a function need to be that returns an element of a List[Any], just Any?

Answer Source

The way you are assigning is correct.

example,

scala> def makeList = List("scala", "clj", 1, 100.5)
makeList: List[Any]

scala> val newList = makeList
newList: List[Any] = List(scala, clj, 1, 100.5)

scala> newList = List("I want to change the reference of list")
<console>:12: error: reassignment to val
       newList = List("I want to change the reference of list")
               ^

in above example newList is val meaning you can't mutate it later.

using var, you can change the reference

scala> def makeList() : List[Any] = List("scala", "clj", 1, 100.5)
makeList: ()List[Any]

scala> var newList = makeList
newList: List[Any] = List(scala, clj, 1, 100.5)

scala> newList = List("I changed the reference of list")
newList: List[Any] = List(I changed the reference of list)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download