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

Scala模式匹配中cons操作符疑问:变量h的定义来源?

Understanding the h Variable in Scala List Pattern Matching

Let’s break this down clearly—your confusion is totally reasonable when you’re first getting comfortable with Scala’s pattern matching!

First, let’s restate the code you’re looking at for reference:

def last[A](l: List[A]): A = l match {
  case h :: Nil => h
  case _ :: tail => last(tail)
  case _ => throw new NoSuchElementException
}

The key thing to realize here is that h is a pattern variable created directly in the match case. Scala’s pattern matching lets you deconstruct data structures (like lists) and bind parts of them to variables right in the case clause—you don’t need to declare these variables beforehand.

Here’s how the first case works:

  • h :: Nil is a pattern that matches a single-element list. Remember, :: is the operator used to prepend an element to a list, so h :: Nil represents a list where h is the only element (since you’re adding it to an empty list Nil).
  • When Scala matches a list against this pattern, it takes the element that’s being prepended to Nil (the only element in the list) and binds it to the variable h. That’s why you can return h immediately—it’s now referencing the last (and only) element of the list.

To put it in simpler terms: imagine you pass the list List(5) to this function. The pattern h :: Nil will match, and Scala will automatically set h = 5 for you, so returning h gives you the last element.

Compare this to the second case _ :: tail:

  • The _ is a wildcard pattern—it matches any element but doesn’t bind it to a variable (we don’t care about the head here, just the remaining list).
  • tail is another pattern variable that gets bound to the rest of the list after the head.

So in short: pattern variables like h and tail are defined right in the case patterns as Scala deconstructs the list structure. You don’t need to declare them elsewhere—Scala handles the binding automatically when the pattern matches.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:48:43