以上答案很好地解释了原因。让我更详细地解释一下。
当您调用val list1 = List(1,2,3) 时,您正在调用一个对象List,它是类List 的伴随对象,它又调用.apply() 方法并返回类List 的实例。
override def apply[A](xs: A*): List[A] = xs.toList //return instance of class List.
现在,如果您查看课程List:
sealed abstract class List[+A] extends AbstractSeq[A] with LinearSeq[A] with Product with GenericTraversableTemplate[A, List] with LinearSeqOptimized[A, List[A]] {...}
你可以看到它继承了 trait LinearSeqOptimized[A, List[A]]。如果你研究这个特性,你可以看到一个apply() 方法
/** Selects an element by its index in the $coll.
* Note: the execution of `apply` may take time proportional to the index value.
* @throws IndexOutOfBoundsException if `idx` does not satisfy `0 <= idx < length`.
*/
def apply(n: Int): A = {
val rest = drop(n)
if (n < 0 || rest.isEmpty) throw new IndexOutOfBoundsException("" + n)
rest.head
}
这意味着,List 类也将继承此 .apply 方法。因此,当您调用list1(1) 时,您实际上是在调用此apply 方法,该方法返回列表的特定索引值。
总之,在第一个代码中,您正在调用伴随对象 List 的 .apply 方法,该方法创建列表并返回类 List 的实例,在第二种情况下,您正在调用类 @987654339 的 .apply 方法@ 返回该列表的特定值。