given/using no Scala 3
Sintaxe moderna.
given/using no Scala 3 é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Scala for Backend Engineering & Functional Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Modern implicits in Scala 3
Scala 3 replaces the overloaded implicit keyword with clearer syntax: given defines an implicit value, and using declares an implicit parameter. The intent is far easier to read.
object Main:
given greeting: String = "Hello"
def greet(name: String)(using g: String): String = s"$g, $name!"
def main(args: Array[String]): Unit =
println(greet("Ann"))given replaces implicit val
Where Scala 2 wrote implicit val x: T = ..., Scala 3 writes given x: T = .... It declares a value available for implicit resolution.
object Main:
given factor: Int = 10
def scale(x: Int)(using f: Int): Int = x * f
def main(args: Array[String]): Unit =
println(scale(5))using replaces implicit parameters
A using clause marks a parameter list as implicit. The compiler fills it from a matching given in scope.
object Main:
given unit: String = "kg"
def label(n: Int)(using u: String): String = s"$n$u"
def main(args: Array[String]): Unit =
println(label(75))Anonymous givens
You can omit the name of a given when you never refer to it directly. The compiler still finds it by type.
object Main:
given Int = 3
def triple(x: Int)(using f: Int): Int = x * f
def main(args: Array[String]): Unit =
println(triple(7))Summoning with summon
Scala 3's summon[T] replaces implicitly[T]. It fetches the given value of type T directly.
object Main:
given name: String = "Scala 3"
def main(args: Array[String]): Unit =
val n = summon[String]
println(n)Anonymous using parameters
If you only need to forward a using parameter, you can leave it unnamed in the clause: (using Int). Summon it inside with summon.
object Main:
given Int = 100
def boosted(x: Int)(using Int): Int = x + summon[Int]
def main(args: Array[String]): Unit =
println(boosted(5))given for type classes
The most idiomatic use of given/using is type classes. Define a trait, provide a given instance, and require it with using.
trait Show[A]:
def show(a: A): String
object Main:
given Show[Int] with
def show(a: Int): String = s"Int($a)"
def display[A](a: A)(using s: Show[A]): String = s.show(a)
def main(args: Array[String]): Unit =
println(display(42))Context bounds still work
Context bounds [A: Show] remain available and desugar to a using parameter. Combine with summon to access the instance.
trait Show[A]:
def show(a: A): String
object Main:
given Show[String] with
def show(a: String): String = s"Str($a)"
def display[A: Show](a: A): String = summon[Show[A]].show(a)
def main(args: Array[String]): Unit =
println(display("hi"))Passing using arguments explicitly
You can supply a using parameter explicitly with the using keyword at the call site, overriding the given in scope.
object Main:
given Int = 10
def scale(x: Int)(using f: Int): Int = x * f
def main(args: Array[String]): Unit =
println(scale(5))
println(scale(5)(using 2))given imports
Scala 3 has dedicated syntax to import givens: import pkg.given or import pkg.{given Show[Int]}. This makes implicit imports explicit and intentional.
object Instances:
given Int = 5
object Main:
import Instances.given
def addBase(x: Int)(using b: Int): Int = x + b
def main(args: Array[String]): Unit =
println(addBase(10))Why the new syntax
In Scala 2 the single keyword implicit meant several different things. Scala 3 splits the concept: given = provide, using = require. Code is clearer and errors are easier to understand.
object Main:
given pi: Double = 3.14159
def area(r: Double)(using p: Double): Double = p * r * r
def main(args: Array[String]): Unit =
println(area(2.0))Quick Check
In Scala 3, which keywords replace implicit for providing and requiring values?
Recap
You learned Scala 3's given/using:
givenprovides an implicit value (replacesimplicit val)usingdeclares an implicit parametersummon[T]replacesimplicitly[T]- Givens can be anonymous and ideal for type classes
import pkg.givenimports them explicitly
Perguntas Frequentes
A aula “given/using no Scala 3” é grátis?
Sim — o texto completo de “given/using no Scala 3” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Scala for Backend Engineering & Functional Programming, atualize para CoddyKit PRO. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.
O que vou aprender em “given/using no Scala 3”?
Sintaxe moderna. Você pratica Scala for Backend Engineering & Functional Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Scala for Backend Engineering & Functional Programming?
Nenhuma experiência prévia é necessária. Scala for Backend Engineering & Functional Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “given/using no Scala 3”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Scala for Backend Engineering & Functional Programming?
Sim. Cada aula de Scala for Backend Engineering & Functional Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Parâmetros implícitos
- given/using no Scala 3
- Conversões implícitas
- Métodos de extensão