Scala模式匹配中cons操作符疑问:变量h的定义来源?
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 :: Nilis a pattern that matches a single-element list. Remember,::is the operator used to prepend an element to a list, soh :: Nilrepresents a list wherehis the only element (since you’re adding it to an empty listNil).- 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 variableh. That’s why you can returnhimmediately—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). tailis 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

