Scala代码中new关键字后::操作符含义及三处::解析疑问
Hey there! Let's unpack those confusing :: symbols in Scala—they're a classic case of Scala's syntax flexibility working both for and against readability at first glance. Let's break this down clearly:
:: Symbols in Scala First ::: The List Instance Method
You got this part right! The first :: is an instance method defined on the List class. A key thing to remember about Scala methods ending in colons is that they're right-associative, meaning x :: myList is actually equivalent to myList.::(x). This method's job is to create a new list with x as the first element (head) and myList as the remaining elements (tail).
Second & Third ::: The Non-Empty List Case Class
Here's where things get tricky, but it's simpler than it looks: both the second and third :: refer to the same thing—a case class that represents a non-empty list.
Scala lets you use operator-like names for classes, and :: (pronounced "cons") is exactly that: a case class that extends List[A], defined roughly like this:
case class ::[A](head: A, tail: List[A]) extends List[A]
- The third
::you see is just the name of this case class in its definition. - The second
::(the one afternew) is using that same class name to instantiate a new non-empty list. When you callnew ::(elem, this)inside the::method, you're creating a new instance of the::case class, withelemas the head and the current list (this) as the tail.
Why This Dual Design?
This setup lets Scala mimic the natural, functional-style list construction you'd see in languages like Haskell, while still sticking to object-oriented principles. When you write 1 :: 2 :: Nil, it reads like "prepend 1 to the list formed by prepending 2 to Nil"—and under the hood, that's exactly what's happening:
val myList = 1 :: 2 :: Nil // Is equivalent to: val tempList = Nil.::(2) // Creates new ::(2, Nil) val myList = tempList.::(1) // Creates new ::(1, tempList)
So to recap:
- When
::is used in a method call (likex :: list), it's the List instance method. - When
::is used afternewor in a class definition, it's the name of the case class that represents non-empty lists.
内容的提问来源于stack exchange,提问作者CodingNow

