You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

Breaking Down the Three :: 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 after new) is using that same class name to instantiate a new non-empty list. When you call new ::(elem, this) inside the :: method, you're creating a new instance of the :: case class, with elem as 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 (like x :: list), it's the List instance method.
  • When :: is used after new or in a class definition, it's the name of the case class that represents non-empty lists.

内容的提问来源于stack exchange,提问作者CodingNow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:31:18