암시적 변환
신중하게 사용합니다
암시적 변환은(는) CoddyKit의 무료 Scala for Backend Engineering & Functional Programming 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Scala for Backend Engineering & Functional Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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
자주 묻는 질문
“암시적 변환” 강의는 무료인가요?
네 — “암시적 변환” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Scala for Backend Engineering & Functional Programming 강의 전체를 잠금 해제할 수 있습니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“암시적 변환”에서 뭘 배우나요?
신중하게 사용합니다 브라우저에서 직접 실행하는 실습 코드로 Scala for Backend Engineering & Functional Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Scala for Backend Engineering & Functional Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Scala for Backend Engineering & Functional Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“암시적 변환” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Scala for Backend Engineering & Functional Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Scala for Backend Engineering & Functional Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.