Сопоставители
Выразительные утверждения
«Сопоставители» — бесплатный урок Scala for Backend Engineering & Functional Programming на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Scala for Backend Engineering & Functional Programming, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Scala for Backend Engineering & Functional Programming содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
What are Matchers?
ScalaTest matchers provide an expressive, English-like syntax for assertions. Instead of assert(x == 3), you write x shouldBe 3, producing readable tests and clear failure messages.
Mixing in Matchers
Mix the Matchers trait into your spec to unlock the DSL. It combines with any testing style.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class DemoSpec extends AnyFlatSpec with Matchers {
"A value" should "equal itself" in {
val x = 3
x shouldBe 3
}
}Equality Matchers
Check equality with shouldBe or should equal. Both compare with == but read naturally.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class EqSpec extends AnyFlatSpec with Matchers {
"sum" should "be correct" in {
(2 + 2) shouldBe 4
(2 + 2) should equal (4)
}
}Comparison Matchers
Numeric comparisons read like prose: should be >, should be <=, and ranges with be within for floating point tolerance.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class CmpSpec extends AnyFlatSpec with Matchers {
"a number" should "compare" in {
7 should be > 3
7 should be <= 7
2.0 shouldBe 2.0 +- 0.01
}
}String Matchers
Matchers for strings include startWith, endWith, include, and regex with fullyMatch regex.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class StrSpec extends AnyFlatSpec with Matchers {
"a string" should "match parts" in {
"hello world" should startWith ("hello")
"hello world" should include ("o w")
"hello world" should endWith ("world")
}
}Collection Matchers
Inspect collections fluently: have size, contain, contain allOf, and emptiness with shouldBe empty.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class ColSpec extends AnyFlatSpec with Matchers {
"a list" should "have expected contents" in {
List(1, 2, 3) should have size 3
List(1, 2, 3) should contain (2)
List.empty[Int] shouldBe empty
}
}Boolean and Option Matchers
Match truthiness and Option contents directly: shouldBe true, shouldBe defined, and should contain for the inner value.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class OptSpec extends AnyFlatSpec with Matchers {
"an option" should "be inspected" in {
Some(5) shouldBe defined
Some(5) should contain (5)
None shouldBe empty
}
}Combining Matchers
Combine expectations with and / or for compound assertions.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class CombineSpec extends AnyFlatSpec with Matchers {
"a number" should "satisfy both" in {
7 should (be > 0 and be < 10)
}
}Testing for Exceptions
Use an [Exception] should be thrownBy { ... } or assertThrows to verify that code fails as expected.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class ExSpec extends AnyFlatSpec with Matchers {
"dividing by zero" should "throw" in {
an [ArithmeticException] should be thrownBy (1 / 0)
}
}Why Matchers Help
Beyond readability, matchers produce descriptive failure messages. A failed List(1,2) should have size 3 reports the expected and actual size, unlike a bare assert that only says the boolean was false.
shouldBe vs should equal
They are nearly identical; shouldBe is terser and gives slightly cleaner messages for simple equality, while should equal supports custom Equality instances for advanced comparisons.
Quick Check
Test your knowledge of matchers.
Recap
You learned ScalaTest matchers:
- Mix in
Matchersfor the DSL. - Equality:
shouldBe,should equal; comparisons withbe >,+- tolerance. - Strings:
startWith,include; collections:have size,contain. - Exceptions:
should be thrownBy. - Matchers give clear, descriptive failures.
Часто задаваемые вопросы
Урок «Сопоставители» бесплатный?
Да — полный текст урока «Сопоставители» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Scala for Backend Engineering & Functional Programming, подпишись на CoddyKit PRO. Курс Scala for Backend Engineering & Functional Programming содержит 4 уроков всего.
Чему я научусь в уроке «Сопоставители»?
Выразительные утверждения Ты практикуешь Scala for Backend Engineering & Functional Programming с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Scala for Backend Engineering & Functional Programming?
Предыдущий опыт не требуется. Scala for Backend Engineering & Functional Programming на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Сопоставители»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Scala for Backend Engineering & Functional Programming?
Да. Каждый урок Scala for Backend Engineering & Functional Programming включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.