零基础学习scala_从0-60开始学习Scala:基础知识

零基础学习scala

by Durga Prasana

通过杜尔加·普拉萨纳(Durga Prasana)

从0-60开始学习Scala:基础知识 (Learn Scala from 0–60: The Basics)

Scala is a general purpose, high-level programming language that offers a balance between developing functional and object-oriented programs.

Scala是一种通用的高级编程语言,可在开发功能性程序和面向对象的程序之间取得平衡。

What is functional programming all about? In simple terms, functions are the first-class citizens in functional programming. In order to extend upon a core set of functionalities of a program, we tend to write additional classes extending upon certain guidelines / interfaces. In functional programming, functions help us achieve the same.

函数式编程的全部意义是什么? 简单来说,函数是函数式编程中的一等公民。 为了扩展程序的一组核心功能,我们倾向于编写在某些准则/接口上扩展的其他类。 在函数式编程中,函数可以帮助我们达到相同的目的。

We’ll use the Scala REPL for all explanations. It is a very handy and informative tool for learning Scala. It logs cute little messages on how our code is interpreted and executed.

我们将使用Scala REPL进行所有说明。 它是学习Scala的非常方便和有用的工具。 它记录有关如何解释和执行我们代码的可爱小消息。

Let’s start with the basics first.

让我们先从基础开始。

1.变量 (1. Variables)

We can define immutable variables using val:

我们可以使用val定义不可变变量:

scala> val name = "King"name: String = King

Mutable variables can be defined and modified using var:

可以使用var定义和修改可变变量:

scala> var name = "King"name: String = King
scala> name = "Arthur"name: String = Arthur

We use def to assign a label to an immutable value whose evaluation is deferred for a later time. It means the label’s value is lazily evaluated every time upon use.

我们使用def将标签分配给不可变值,该值的评估推迟到以后。 这意味着每次使用时都会对标签的值进行延迟评估。

scala> var name = "King"name: String = King
scala> def alias = namealias: String
scala> aliasres2: String = King

Did you observe something interesting?

你有没有发现有趣的事情?

While defining alias, no value was assigned to alias: String since it is lazily associated, when we invoke it. What would happen if we change the value of name?

在定义alias ,未将任何值分配给alias: String因为当我们调用它时,它是延迟关联的。 如果更改name的值会怎样?

scala> aliasres5: String = King
scala> name = "Arthur, King Arthur"name: String = Arthur, King Arthur
scala> aliasres6: String = Arthur, King Arthur
2.控制流程 (2. Control flow)

We use control flow statements to express our decision logic.

我们使用控制流语句来表达我们的决策逻辑。

You can write an if-else statement as below:

您可以编写一条if-else语句,如下所示:

if(name.contains("Arthur")) {  print("Entombed sword")} else {  print("You're not entitled to this sword")}

Or, you can use while:

或者,您可以使用while

var attempts = 0while (attempts < 3) {  drawSword()  attempts += 1}
3.馆藏 (3. Collections)

Scala explicitly distinguishes between immutable versus mutable collections — right from the package namespace itself ( scala.collection.immutable or scala.collection.mutable).

Scala明确区分不可变集合和可变集合-从包名称空间本身( scala.collection.immutablescala.collection.mutable )开始。

Unlike immutable collections, mutable collections can be updated or extended in place. This enables us to change, add, or remove elements as a side effect.

与不可变集合不同,可变集合可以在适当位置进行更新或扩展。 这使我们能够更改,添加或删除元素作为副作用。

But performing addition, removal, or update operations on immutable collections returns a new collection instead.

但是,对不可变集合执行添加,删除或更新操作将返回一个新集合。

Immutable collections are always automatically imported via the scala._ (which also contains alias for scala.collection.immutable.List).

不可变集合总是通过scala._ (也包含scala.collection.immutable.List别名)自动导入。

However, to use mutable collections, you need to explicitly import scala.collection.mutable.List.

但是,要使用可变集合,您需要显式导入scala.collection.mutable.List

In the spirit of functional programming, we’ll primarily base our examples on immutable aspects of the language, with minor detours into the mutable side.

本着函数式编程的精神,我们将主要基于不可变的语言方面编写示例,并在可变方面稍作绕道。

清单 (List)

We can create a list in various ways:

我们可以通过多种方式创建列表:

scala> val names = List("Arthur", "Uther", "Mordred", "Vortigern")
names: List[String] = List(Arthur, Uther, Mordred, Vortigern)

Another handy approach is to define a list using the cons :: operator. This joins a head element with the remaining tail of a list.

另一个方便的方法是使用cons ::运算符定义列表。 这将head元素与列表的其余尾部连接在一起。

scala> val name = "Arthur" :: "Uther" :: "Mordred" :: "Vortigern" :: Nil
name: List[String] = List(Arthur, Uther, Mordred, Vortigern)

Which is equivalent to:

等效于:

scala> val name = "Arthur" :: ("Uther" :: ("Mordred" :: ("Vortigern" :: Nil)))
name: List[String] = List(Arthur, Uther, Mordred, Vortigern)

We can access list elements directly by their index. Remember Scala uses zero-based indexing:

我们可以直接通过其索引访问列表元素。 请记住,Scala使用基于零的索引:

scala> name(2)
res7: String = Mordred

Some common helper methods include:

一些常见的辅助方法包括:

list.head, which returns the first element:

list.head ,它返回第一个元素:

scala> name.head
res8: String = Arthur

list.tail, which returns the tail of a list (which includes everything except the head):

list.tail ,它返回列表的尾部(包括头部以外的所有内容):

scala> name.tail
res9: List[String] = List(Uther, Mordred, Vortigern)
(Set)

Set allows us to create a non-repeated group of entities. List doesn’t eliminate duplicates by default.

Set允许我们创建一个非重复的实体组。 默认情况下, List不会消除重复项。

scala> val nameswithDuplicates = List("Arthur", "Uther", "Mordred", "Vortigern", "Arthur", "Uther")
nameswithDuplicates: List[String] = List(Arthur, Uther, Mordred, Vortigern, Arthur, Uther)

Here, ‘Arthur’ is repeated twice, and so is ‘Uther’.

在这里,“亚瑟”重复两次,“乌瑟尔”重复两次。

Let’s create a Set with the same names. Notice how it excludes the duplicates.

让我们创建一个具有相同名称的Set。 请注意,它如何排除重复项。

scala> val uniqueNames = Set("Arthur", "Uther", "Mordred", "Vortigern", "Arthur", "Uther")
uniqueNames: scala.collection.immutable.Set[String] = Set(Arthur, Uther, Mordred, Vortigern)

We can check for the existence of specific element in Set using contains():

我们可以使用contains()检查Set中特定元素的存在:

scala> uniqueNames.contains("Vortigern")res0: Boolean = true

We can add elements to a Set using the + method (which takes varargs i.e. variable-length arguments)

我们可以使用+方法(使用varargs变长度参数)将元素添加到Set中。

scala> uniqueNames + ("Igraine", "Elsa", "Guenevere")res0: scala.collection.immutable.Set[String] = Set(Arthur, Elsa, Vortigern, Guenevere, Mordred, Igraine, Uther)

Similarly we can remove elements using the - method

同样,我们可以使用-方法删除元素

scala> uniqueNames - "Elsa"
res1: scala.collection.immutable.Set[String] = Set(Arthur, Uther, Mordred, Vortigern)
地图 (Map)

Map is an iterable collection which contains mappings from key elements to respective value elements, which can be created as:

Map是一个可迭代的集合,其中包含从key元素到各个value元素的映射,可以将其创建为:

scala> val kingSpouses = Map( | "King Uther" -> "Igraine", | "Vortigern" -> "Elsa", | "King Arthur" -> "Guenevere" | )
kingSpouses: scala.collection.immutable.Map[String,String] = Map(King Uther -> Igraine, Vortigern -> Elsa, King Arthur -> Guenevere)

Values for a specific key in map can be accessed as:

映射中特定键的值可以通过以下方式访问:

scala> kingSpouses("Vortigern")res0: String = Elsa

We can add an entry to Map using the + method:

我们可以使用+方法向Map添加一个条目:

scala> kingSpouses + ("Launcelot" -> "Elaine")res0: scala.collection.immutable.Map[String,String] = Map(King Uther -> Igraine, Vortigern -> Elsa, King Arthur -> Guenevere, Launcelot -> Elaine)

To modify an existing mapping, we simply re-add the updated key-value:

要修改现有的映射,我们只需重新添加更新的键值即可:

scala> kingSpouses + ("Launcelot" -> "Guenevere")res1: scala.collection.immutable.Map[String,String] = Map(King Uther -> Igraine, Vortigern -> Elsa, King Arthur -> Guenevere, Launcelot -> Guenevere)

Note that since the collection is immutable, each edit operation returns a new collection( res0, res1) with the changes applied. The original collection kingSpouses remains unchanged.

请注意,由于该集合是不可变的,因此每个编辑操作都会返回一个新的集合( res0res1 ),并应用更改。 最初的收藏者kingSpouses保持不变。

4.功能组合器 (4. Functional combinators)

Now that we’ve learned how to group a set of entities together, let’s see how we can use functional combinators to generate meaningful transformations on such collections.

现在,我们已经学习了如何将一组实体组合在一起,让我们看看如何使用功能组合器在此类集合上生成有意义的转换。

In John Hughes’ simple words:

用约翰·休斯的简单话来说:

A combinator is a function which builds program fragments from program fragments.
组合器是一种从程序片段构建程序片段的功能。

An in-depth look at how combinators work is outside of this article’s scope. But, we’ll try to touch upon a high-level understanding of the concept anyhow.

深入了解组合器的工作方式不在本文的讨论范围之内。 但是,无论如何,我们都将尝试深入理解该概念。

Let’s take an example.

让我们举个例子。

Suppose we want to find names of all queens using the kingSpouses collection map that we created.

假设我们想使用我们创建的kingSpouses集合图查找所有皇后的名字。

We’d want to do something along the lines of examining each entry in the map. If the key has the name of a king, then we’re interested in the name of it’s spouse (i.e. queen).

我们希望按照检查地图中每个条目的方式进行操作。 如果key有国王的名字,那么我们就对它的配偶(即女王)的名字感兴趣。

We shall use the filter combinator on map, which has a signature like:

我们将在地图上使用filter组合filter ,其签名类似:

collection.filter( /* a filter condition method which returns true on matching map entries */)

Overall we shall perform the following steps to find queens:

总的来说,我们将执行以下步骤来查找皇后:

  • Find the (key, value) pairs with kings’ names as keys.

    查找以国王的名字为键的(键,值)对。
  • Extract the values (names of queen) only for such tuples.

    仅提取此类元组的值(皇后名称)。

The filter is a function which, when given a (key, value), returns true / false.

filter是一个函数,当给定一个(键,值)时,它返回true / false。

  1. Find the map entries pertaining to kings.

    查找与国王有关的地图条目。

Let’s define our filtering predicate function. Since key_value is a tuple of (key, value), we extract the key using ._1 (and guess what ._2 returns?)

让我们定义我们的过滤谓词函数。 由于key_value是(key,value)的元组,因此我们使用._1提取密钥(并猜测._2返回什么?)

scala> def isKingly(key_value: (String, String)): Boolean = key_value._1.toLowerCase.contains("king")
isKingly: (key_value: (String, String))Boolean

Now we shall use the filter function defined above to filter kingly entries.

现在我们将使用上面定义的过滤器功能filter国王条目。

scala> val kingsAndQueens = kingSpouses.filter(isKingly)
kingsAndQueens: scala.collection.immutable.Map[String,String] = Map(King Uther -> Igraine, King Arthur -> Guenevere)

2. Extract the names of respective queens from the filtered tuples.

2.从过滤后的元组中提取各个皇后的名称。

scala> kingsAndQueens.values
res10: Iterable[String] = MapLike.DefaultValuesIterable(Igraine, Guenevere)

Let’s print out the names of queens using the foreach combinator:

让我们使用foreach组合器打印出女王的名字:

scala> kingsAndQueens.values.foreach(println)IgraineGuenevere

Some other useful combinators are foreach, filter, zip, partition, find.

其他一些有用的组合器是foreachfilterzippartitionfind

We shall re-visit some of these after having learnt how to define functions and passing functions as arguments to other functions in higher-order functions.

在学习了如何定义函数并将函数作为参数传递给高阶函数中的其他函数之后,我们将重新讨论其中的一些。

Let’s recap on what we’ve learned:

让我们回顾一下我们学到的东西:

  • Different ways of defining variables

    定义变量的不同方法
  • Various control-flow statements

    各种控制流语句
  • Some basics about various collections

    有关各种收藏的一些基础知识
  • Overview of using functional combinators on collections

    在集合上使用功能组合器的概述

I hope you found this article useful. It is first in a series of articles to follow on learning Scala.

希望本文对您有所帮助。 这是学习Scala的系列文章中的第一篇。

In part two, we’ll learn about defining classes, traits, encapsulation and other object-oriented concepts.

在第二部分中,我们将学习定义类,特征,封装和其他面向对象的概念。

Please feel free to let me know your feedback and suggestions on how I can improve the content. Until then, ❤ coding.

请随时让我知道您对我如何改进内容的反馈和建议。 在那之前,❤编码。

翻译自: https://www.freecodecamp.org/news/learning-scala-from-0-60-part-i-dc095d274b78/

零基础学习scala

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值