在理解 Scala 代码片段方面需要帮助 [英] Need help in understanding a scala code snippet

查看:40
本文介绍了在理解 Scala 代码片段方面需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
谁能解释一下符号=";在 Scala 中使用

val list = List("abc", "cde", "fg")
list.count (s => s.length == 3)

上面的代码片段返回list中长度等于3的字符串元素的数量.但是我无法理解该代码段,因为我无法在这种情况下掌握 => 运算符的用法.任何解释都会非常有帮助.

The above code snippet returns the number of string elements in list whose length is equal to 3. But I'm not able to understand the snippet as I'm having trouble to grasp the usage of the => operator in this context. Any explanation will be realy helpful.

推荐答案

是的,Scala 可能很难理解.我会尽我所能解释它,尽管我也可能不正确.

Yeah, Scala can be pretty hard to understand. I'll do my best to explain it, though I might not get it right either.

List.count 方法将返回布尔值的 block 代码作为参数.

The List.count method takes as a parameter a block of code that returns a boolean.

块只是一小段代码,可以通过多种方式创建,例如将代码包含在 { }

Blocks are just little snippets of code and can be created in many ways eg by enclosing code in { }

在 Scala 文档中,这被描述为

In the scala docs this is described as

def count (p : (A) => Boolean) : Int

so count 接受一个参数 p 这是一个接受 A 类型的参数并返回一个 Boolean 的块代码>

so count takes a parameter p which is a block that takes an argument of type A and returns a Boolean

所以在这个例子中:

s => s.length == 3

是一个 block 代码.块通常遵循格式

is a block of code. Blocks usually follow the format

[arguments] => [Code to execute]

所以在这个例子中 s 是块的输入,s.length == 3 是应该返回一个布尔值的代码.您可以随意命名参数,只要它们的顺序正确即可.

So in this instance s is the input to the block and s.length == 3 is the code that should return a boolean. You can name the arguments whatever you like, so long as they are in the correct order.

当使用迭代集合的方法时,例如 countmapeach 等,传递的参数将是当前的它正在迭代的集合中的项目.

When using a method that iterates over a collection, eg count, map, each, etc, the argument passed will be the current item in the collection it is iterating over.

如果您想了解更多相关信息,您应该查看我的 Martin Odersky(scala 的创建者)正在开设的 Coursera 课程,并将详细介绍此类细节:https://www.coursera.org/course/progfun

If you want to learn more about it you should check out the Coursera course that is being run my Martin Odersky (the creator of scala) and will be covering details like this in great detail: https://www.coursera.org/course/progfun

这篇关于在理解 Scala 代码片段方面需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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