E026: Auxiliary Constructor Needs Non-Implicit Parameter — 보조 생성자에는 비-암시적 파라미터가 필요해요
E026: Auxiliary Constructor Needs Non-Implicit Parameter — 보조 생성자에는 비-암시적 파라미터가 필요해요
보조 생성자(auxiliary constructor, 이차 생성자) 가 암시적(implicit) 파라미터 목록만 갖고 있고, 비-암시적 파라미터를 하나도 갖지 않을 때 이 에러가 나와요. 생성자 파라미터 목록은 암시적 파라미터만으로 이루어지면 안 된다는 뜻이에요.
본문
생성자 가운데 기본 생성자(primary constructor) 만 암시적 파라미터만으로 이루어진 목록을 가질 수 있어요. 보조 생성자는 반드시 비-암시적 파라미터 목록을 하나 이상 가져야 해요. 그리고 기본 생성자가 암시적 인자 목록(implicit argslist)을 가진다면, 그 기본 생성자를 호출하는 보조 생성자는 암시적 값을 명시적으로 지정해 줘야 해요.
예제 (Example)
class Example(implicit x: Int):
def this(implicit x: String, y: Int) = this()(using y)
오류 메시지 (Error)
-- [E026] Syntax Error: example.scala:2:39 -------------------------------------
2 | def this(implicit x: String, y: Int) = this()(using y)
| ^
| Auxiliary constructor needs non-implicit parameter list
|-----------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| Only the primary constructor is allowed an implicit parameter list;
| auxiliary constructors need non-implicit parameter lists. When a primary
| constructor has an implicit argslist, auxiliary constructors that call the
| primary constructor must specify the implicit value.
|
| To resolve this issue check for:
| - Forgotten parenthesis on this (def this() = { ... })
| - Auxiliary constructors specify the implicit value
-----------------------------------------------------------------------------
해결 방법 (Solution)
보조 생성자에 빈 비-암시적 파라미터 목록을 앞에 추가하거나, 타입이 다른 비-암시적 파라미터를 명시적으로 넣어주면 돼요.
// Add an empty non-implicit parameter list before the implicit one
class Example(implicit x: Int):
def this()(implicit x: String, y: Int) = this()(using y)
// Alternative: use an explicit non-implicit parameter with a different type
class Example(implicit x: Int):
def this(x: String, y: Int) = this()(using y)