且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在理解 Scala 代码片段方面需要帮助

更新时间:2023-02-26 16:42:01

是的,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