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:
val tmp = List.apply[Int](1,2,3)
In the expression List.apply(1,2,3), List is 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:
object List extends SeqFactory[List] {
...
override def apply[A](xs: A*): List[A] = xs.toList
When you write List[Int].apply(1,2,3), Scala interprets that as (List[Int]).apply(1,2,3). And List[Int] is interpreted as if it were List[Int]() without the parentheses, which is equivalent to List.apply[Int]. Since apply requires an argument, Scala gives you an error telling you that it's missing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With