E012: 암시적 클래스 주 생성자 인자 수
E012: 암시적 클래스 주 생성자 인자 수 (Implicit Class Primary Constructor Arity)
이 에러는 암시적 클래스(implicit class)의 주 생성자에 non-implicit 파라미터가 둘 이상 있을 때 발생해요. 암시적 클래스는 정확히 하나의 주 생성자 파라미터를 받아야 해요. 이 제한이 있는 이유는 암시적 클래스가 한 타입의 단일 값을 다른 타입으로 변환하는 암시적 변환(implicit conversion)을 위해 설계됐기 때문이에요.
본문
non-implicit 인자를 둘 이상 가진 암시적 클래스를 만드는 것이 가능하긴 하지만, 그런 클래스는 암시적 탐색(implicit lookup) 중에 사용되지 않아요.
Example
object Implicits:
implicit class Wrapper(a: Int, b: String):
def combined: String = s"$a-$b"
Error
-- [E012] Syntax Error: example.scala:2:17 -------------------------------------
2 | implicit class Wrapper(a: Int, b: String):
| ^
| Implicit classes must accept exactly one primary constructor parameter
|
3 | def combined: String = s"$a-$b"
|-----------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| Implicit classes may only take one non-implicit argument in their constructor. For example:
|
| implicit class RichDate(date: java.util.Date)
|
| While it’s possible to create an implicit class with more than one non-implicit argument,
| such classes aren’t used during implicit lookup.
-----------------------------------------------------------------------------
Solution
// Use exactly one parameter
object Implicits:
implicit class RichInt(val value: Int):
def doubled: Int = value * 2
import Implicits.*
val result = 42.doubled
// Additional parameters can be implicit
object Implicits:
implicit class Formatter(val value: Int)(using format: String = "%d"):
def formatted: String = format.format(value)
import Implicits.*
val result = 42.formatted
// In Scala 3, prefer extension methods
extension (value: Int)
def doubled: Int = value * 2
val result = 42.doubled
더 알아보기
- 암시적 클래스의 제약사항에 대한 자세한 내용은 Scala 2 문서의 "Implicit Classes"를 참고하세요.
- Scala 3에서는 확장 메서드가 더 권장되는 방식이에요.