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

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
}