E159: trait은 native 메서드를 정의할 수 없어요

E159: trait은 native 메서드를 정의할 수 없어요 (Trait May Not Define Native Method)

trait이 @native 애너테이션을 붙인 메서드를 정의하려 할 때 발생하는 에러예요.

출처: Scala 3 Reference

본문

native 메서드는 플랫폼 특화 코드(예: JNI를 통한 C나 어셈블리)로 구현되며 구체적인 class 구현이 필요해요. trait은 여러 클래스에 믹스인(mix-in)될 수 있고, native 코드를 위한 직접적인 JVM 구현 경로가 없기 때문에 native 메서드를 정의할 수 없어요.

Example

trait NativeOperations {
  @native def performNativeOp(): Unit
}

Error

-- [E159] Syntax Error: example.scala:2:14 -------------------------------------
2 |  @native def performNativeOp(): Unit
  |              ^
  |              A trait cannot define a @native method.

Solution

// Define native methods in a class or object instead
class NativeOperations {
  @native def performNativeOp(): Unit
}
// Or use an abstract method in the trait and implement it in a class
trait NativeOperations {
  def performNativeOp(): Unit
}

class NativeImpl extends NativeOperations {
  @native def performNativeOp(): Unit
}

더 알아보기

  • @native 애너테이션과 JNI 상호운용에 대한 자세한 내용은 Java/Scala 상호운용 문서를 참고하세요.