Back to Scala3

E159: Trait May Not Define Native Method

docs/_docs/reference/error-codes/E159.md

3.8.41.4 KB
Original Source

E159: Trait May Not Define Native Method

This error occurs when a trait attempts to define a method with the @native annotation.

Native methods are implemented in platform-specific code (like C or assembly through JNI) and require a concrete class implementation. Since traits can be mixed into multiple classes and don't have a direct JVM implementation path for native code, they cannot define native methods.


Example

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

Error

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

Solution

scala
// Define native methods in a class or object instead
class NativeOperations {
  @native def performNativeOp(): Unit
}
scala
// 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
}
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>