Определение экземпляров
Неявные экземпляры
«Определение экземпляров» — бесплатный урок 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 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Defining Instances
An instance tells the compiler how a type class behaves for a specific type. In Scala, instances are usually marked implicit (Scala 2) or declared with given (Scala 3) so they are found automatically.
An implicit val Instance
For a simple type class, an implicit val is enough. The compiler finds it when a function needs a Show[Int].
trait Show[A] { def show(a: A): String }
object Main {
implicit val intShow: Show[Int] = (a: Int) => s"Int=$a"
def display[A](a: A)(implicit s: Show[A]): String = s.show(a)
def main(args: Array[String]): Unit = {
println(display(123))
}
}implicitly: Summon an Instance
implicitly[Show[Int]] asks the compiler to fetch the in-scope instance. It is useful for testing that an instance exists or for accessing it directly.
trait Show[A] { def show(a: A): String }
object Main {
implicit val intShow: Show[Int] = (a: Int) => s"<$a>"
def main(args: Array[String]): Unit = {
val s = implicitly[Show[Int]]
println(s.show(8))
}
}Instances for Custom Types
Define an instance for your own case class. The data class stays clean; the formatting lives in the instance.
trait Show[A] { def show(a: A): String }
case class Point(x: Int, y: Int)
object Main {
implicit val pointShow: Show[Point] = (p: Point) => s"(${p.x}, ${p.y})"
def display[A](a: A)(implicit s: Show[A]): String = s.show(a)
def main(args: Array[String]): Unit = {
println(display(Point(3, 4)))
}
}implicit def for Generic Instances
When an instance depends on another instance, use implicit def. Here a Show[List[A]] is built from a Show[A].
trait Show[A] { def show(a: A): String }
object Main {
implicit val intShow: Show[Int] = (a: Int) => a.toString
implicit def listShow[A](implicit s: Show[A]): Show[List[A]] =
(xs: List[A]) => xs.map(s.show).mkString("[", ", ", "]")
def display[A](a: A)(implicit s: Show[A]): String = s.show(a)
def main(args: Array[String]): Unit = {
println(display(List(1, 2, 3)))
}
}Instances in the Companion Object
Placing instances in the type class's companion object means they are found automatically without any import. This is the recommended home for default instances.
trait Show[A] { def show(a: A): String }
object Show {
implicit val intShow: Show[Int] = (a: Int) => s"i:$a"
implicit val strShow: Show[String] = (a: String) => s"s:$a"
}
object Main {
def display[A](a: A)(implicit s: Show[A]): String = s.show(a)
def main(args: Array[String]): Unit = {
println(display(5))
println(display("hi"))
}
}Implicit Scope and Priority
The compiler searches several places for an instance: the local/imported scope first, then the companion objects of the types involved. If two instances are equally specific, you get an ambiguous implicit error.
Context Bound Shorthand
The syntax def f[A: Show](a: A) is a context bound: it means there must be an implicit Show[A] in scope. Inside, retrieve it with implicitly.
trait Show[A] { def show(a: A): String }
object Main {
implicit val intShow: Show[Int] = (a: Int) => s"n=$a"
def display[A: Show](a: A): String = implicitly[Show[A]].show(a)
def main(args: Array[String]): Unit = {
println(display(77))
}
}A Summoner Helper
Libraries add an apply method to the companion as a convenient summoner: Show[Int] returns the instance. It is cleaner than implicitly.
trait Show[A] { def show(a: A): String }
object Show {
def apply[A](implicit s: Show[A]): Show[A] = s
implicit val intShow: Show[Int] = (a: Int) => s"=$a"
}
object Main {
def main(args: Array[String]): Unit = {
println(Show[Int].show(10))
}
}Avoiding Orphan Instances
An orphan instance is one defined neither with the type class nor with the type. They are legal but can cause inconsistent behavior across imports. Prefer companion-object instances to keep them coherent.
Putting It Together
A complete program: companion-object instances, a derived list instance, and a summoner.
trait Show[A] { def show(a: A): String }
object Show {
def apply[A](implicit s: Show[A]): Show[A] = s
implicit val intShow: Show[Int] = _.toString
implicit def listShow[A](implicit s: Show[A]): Show[List[A]] =
(xs: List[A]) => xs.map(s.show).mkString(", ")
}
object Main {
def main(args: Array[String]): Unit = {
println(Show[List[Int]].show(List(4, 5, 6)))
}
}Quick Check
Test your knowledge of defining instances.
Recap
You learned to define instances:
implicit valfor simple instances,implicit deffor derived ones.- Summon with
implicitlyor a companionapply. - Use context bounds
[A: Show]as shorthand. - Put instances in companion objects to avoid orphans.
Часто задаваемые вопросы
Урок «Определение экземпляров» бесплатный?
Да — полный текст урока «Определение экземпляров» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 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 — локальная установка не требуется.
Все уроки этого курса
- Шаблон классов типов
- Определение экземпляров
- Распространённые классы типов
- Выведение классов типов