I’m new to Scala, coming from python and trying to wrap my head around some of the syntax and conventions. I’m curious why the following doesn’t work:
scala> val tmp = List[Int].apply(1,2,3)
<console>:7: error: missing arguments for method apply in object List;
follow this method with `_' if you want to treat it as a partially applied function
val tmp = List[Int].apply(1,2,3)
Yet, when I do the following, I get no error:
scala> val tmp = List.apply(1,2,3)
tmp: List[Int] = List(1,2,3)
scala> val tmp = List[Int](1,2,3)
tmp: List[Int] = List(1,2,3)
Why does List[Int].apply() give me an error?
Thanks for your help!
Because your syntax is wrong. If you want the equivalent of
List.apply(1,2,3), then it should be:In the expression
List.apply(1,2,3),Listis referencing the companion object, and objects can’t have generics. Thus, you have to put the generic on the method.For reference, you can see this in the source code for
List:When you write
List[Int].apply(1,2,3), Scala interprets that as(List[Int]).apply(1,2,3). AndList[Int]is interpreted as if it wereList[Int]()without the parentheses, which is equivalent toList.apply[Int]. Sinceapplyrequires an argument, Scala gives you an error telling you that it’s missing.