简体   繁体   中英

Lombok @EqualsAndHashCode with Scala - case class cannot inherit Java class

I have a Java class, with a lombok generated equals and hashCode

@EqualsAndHashCode
@AllArgsConstructor
public class MyJavaClass {
    private final String foo;
}

And a Scala case class which inherits this:

case class MyScalaCaseClass(foo: String, bar: String) extends MyJavaClass(foo)

I get the following compile time error:

[scalac-2.12] .../MyScalaCaseClass.scala:5: error: overriding method canEqual in trait Equals of type (that: Any)Boolean;
[scalac-2.12]  method canEqual in class MyJavaClass of type (x$1: Any)Boolean has weaker access privileges; it should be public
[scalac-2.12] case class MyScalaCaseClass(foo: String, bar: String) extends MyJavaClass(foo)
[scalac-2.12]            ^
[scalac-2.12] one error found

It seems that this issue seems to be caused by a mismatch of access privilages:

  • I'm using Lombok 1.16, and it seems since 1.14 the canEqual method generated by Lombok is protected ( the Lombok docs mention this too)

  • The Scala Equals trait has a public canEqual method.

The Lombok Docs explicitly mention interoperability with Scala case classes:

If all classes in a hierarchy are a mix of scala case classes and classes with lombok-generated equals methods, all equality will 'just work'.

Is there anything I'm missing here? I can work around this by using a class rather than a case class , but then I'd have to implement equals which doesn't seem so elegant.

Maybe you can override canEqual method in MyJavaClass for replacing lombok generated canEqual method like:

public boolean canEqual(Object other) {
    return other instanceof MyJavaClass;
}

This way will keep canEqual method has the public modifier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM