0Pricing
Scala for Backend Engineering & Functional Programming · Aula

Conversões implícitas

Use com cuidado.

Conversões implícitas é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 3 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.

What is an implicit conversion?

An implicit conversion automatically transforms a value of one type into another when the compiler needs it. It can make APIs more convenient, but it must be used with care because it hides what is happening.

object Main {
  import scala.language.implicitConversions
  implicit def intToString(x: Int): String = s"number-$x"
  def main(args: Array[String]): Unit = {
    val s: String = 42
    println(s)
  }
}

How the compiler uses them

When a value's type does not match what is expected, the compiler searches for an implicit conversion that fixes the mismatch and inserts it silently.

object Main {
  import scala.language.implicitConversions
  implicit def doubleToInt(d: Double): Int = d.toInt
  def addTen(x: Int): Int = x + 10
  def main(args: Array[String]): Unit = {
    println(addTen(3.9))
  }
}

Enabling the feature

Defining implicit conversions requires importing scala.language.implicitConversions, or the compiler warns you. This is a deliberate friction to discourage overuse.

object Main {
  import scala.language.implicitConversions
  case class Celsius(value: Double)
  implicit def doubleToCelsius(d: Double): Celsius = Celsius(d)
  def describe(c: Celsius): String = s"${c.value} C"
  def main(args: Array[String]): Unit = {
    println(describe(36.6))
  }
}

Wrapping for extra methods (old style)

Before extension methods, implicit conversions to a wrapper class were the way to 'add' methods to existing types, the so-called pimp-my-library pattern.

object Main {
  import scala.language.implicitConversions
  class RichInt2(x: Int) {
    def squared: Int = x * x
  }
  implicit def toRich(x: Int): RichInt2 = new RichInt2(x)
  def main(args: Array[String]): Unit = {
    println(5.squared)
  }
}

The danger: silent surprises

Because conversions are invisible at the call site, they can cause confusing behavior and bugs that are hard to trace. A typo might compile by accidentally triggering a conversion.

object Main {
  import scala.language.implicitConversions
  implicit def boolToInt(b: Boolean): Int = if (b) 1 else 0
  def main(args: Array[String]): Unit = {
    val total = true + 4 // surprising! becomes 1 + 4
    println(total)
  }
}

Prefer explicit conversion

Often the safest choice is a plain named method instead of an implicit. The code is longer but obvious to readers.

object Main {
  case class Celsius(value: Double)
  def fromDouble(d: Double): Celsius = Celsius(d)
  def main(args: Array[String]): Unit = {
    val c = fromDouble(20.5)
    println(c)
  }
}

Scala 3: the Conversion type class

Scala 3 makes conversions explicit via a given Conversion[A, B] instance. This is clearer about intent and still requires the language import.

import scala.language.implicitConversions

object Main:
  given Conversion[Int, String] = (x: Int) => s"val-$x"
  def main(args: Array[String]): Unit =
    val s: String = 7
    println(s)

Conversions only apply once

The compiler applies at most one implicit conversion at a time. It will not chain two conversions to bridge a gap, which limits surprises.

object Main {
  import scala.language.implicitConversions
  implicit def intToStr(x: Int): String = x.toString
  def needString(s: String): Int = s.length
  def main(args: Array[String]): Unit = {
    println(needString(12345))
  }
}

Where conversions are found

Like other implicits, conversions are resolved from local scope, imports, and companion objects. Keeping them in a clearly named import makes their presence visible.

object Conversions:
  import scala.language.implicitConversions
  implicit def strToLen(s: String): Int = s.length

object Main:
  import Conversions._
  def main(args: Array[String]): Unit =
    val n: Int = "hello"
    println(n)

When conversions are reasonable

Legitimate uses include interoperating with Java types, numeric widening helpers, and library boundaries. Outside those, prefer extension methods or explicit functions.

object Main {
  import scala.language.implicitConversions
  case class Meters(v: Double)
  implicit def metersToDouble(m: Meters): Double = m.v
  def main(args: Array[String]): Unit = {
    val d: Double = Meters(3.5)
    println(d * 2)
  }
}

Rule of thumb

If a reader cannot tell from the code that a conversion happens, that is a warning sign. Reach for implicit conversions last, after extension methods and explicit calls.

object Main {
  // Explicit and obvious - usually better
  case class Price(cents: Int)
  def toDollars(p: Price): Double = p.cents / 100.0
  def main(args: Array[String]): Unit = {
    println(toDollars(Price(1599)))
  }
}

Quick Check

What is the main risk of implicit conversions?

Recap

You learned implicit conversions and their caveats:

  • They auto-convert one type to another when types mismatch
  • Require import scala.language.implicitConversions
  • Scala 3 uses given Conversion[A, B]
  • Only one conversion is applied at a time
  • Use them sparingly; prefer extension methods or explicit calls

Perguntas Frequentes

A aula “Conversões implícitas” é grátis?

Sim — o texto completo de “Conversões implícitas” é 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 “Conversões implícitas”?

Use com cuidado. 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 3 de 4.

Quanto tempo leva a aula “Conversões implícitas”?

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

  1. Parâmetros implícitos
  2. given/using no Scala 3
  3. Conversões implícitas
  4. Métodos de extensão
← Voltar para Scala for Backend Engineering & Functional Programming