Scala 的隐藏特性 [英] Hidden features of Scala

查看:61
本文介绍了Scala 的隐藏特性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每位 Scala 开发人员都应该了解 Scala 的哪些隐藏功能?

What are the hidden features of Scala that every Scala developer should be aware of?

请为每个答案添加一个隐藏功能.

One hidden feature per answer, please.

推荐答案

好吧,我不得不再添加一个.Scala 中的每个 Regex 对象都有一个提取器(参见上面 oxbox_lakes 的答案),可让您访问匹配组.因此,您可以执行以下操作:

Okay, I had to add one more. Every Regex object in Scala has an extractor (see answer from oxbox_lakes above) that gives you access to the match groups. So you can do something like:

// Regex to split a date in the format Y/M/D.
val regex = "(\\d+)/(\\d+)/(\\d+)".r
val regex(year, month, day) = "2010/1/13"

如果您不习惯使用模式匹配和提取器,那么第二行看起来会令人困惑.每当您定义 valvar 时,关键字后面的内容不仅仅是一个标识符,而是一个模式.这就是为什么这样做:

The second line looks confusing if you're not used to using pattern matching and extractors. Whenever you define a val or var, what comes after the keyword is not simply an identifier but rather a pattern. That's why this works:

val (a, b, c) = (1, 3.14159, "Hello, world")

右手表达式创建了一个 Tuple3[Int, Double, String] 可以匹配模式 (a, b, c).

The right hand expression creates a Tuple3[Int, Double, String] which can match the pattern (a, b, c).

大多数情况下,您的模式使用作为单例对象成员的提取器.例如,如果你写一个像

Most of the time your patterns use extractors that are members of singleton objects. For example, if you write a pattern like

Some(value)

然后你隐式调用提取器Some.unapply.

then you're implicitly calling the extractor Some.unapply.

但是您也可以在模式中使用类实例,这就是这里发生的事情.val regex 是 Regex 的一个实例,当您在模式中使用它时,您隐式调用了 regex.unapplySeq(unapplyunapplySeq 超出了本答案的范围),它将匹配组提取到 Seq[String] 中,其中的元素按顺序分配给变量 year、month,和一天.

But you can also use class instances in patterns, and that is what's happening here. The val regex is an instance of Regex, and when you use it in a pattern, you're implicitly calling regex.unapplySeq (unapply versus unapplySeq is beyond the scope of this answer), which extracts the match groups into a Seq[String], the elements of which are assigned in order to the variables year, month, and day.

这篇关于Scala 的隐藏特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆