我正在努力将 Web 项目从
Java
迁移到 Kotlin
。在此过程中,我遇到了编译问题,这可能会在将来产生问题,尤其是现有项目必须重用 Kotlin 组件的情况下。
我用简单的方式本地化并重现了这个问题:
Kotlin 版本:
1.9.23
有
EntityId
这是内联值类
@JvmInline
value class EntityId(val id: UUID)
以及包含带有
EntityId
的抽象函数的 Kotlin 接口
interface KotlinInterface<T> {
fun findById(id: EntityId): T
}
我尝试通过以下方式实现这个接口 Java(因为 java 不支持 kotlin 值类,编译器期望
UUID
类型而不是 EntityId
):
public class JavaImpl implements KotlinInterface<Entity> {
@Override
public Entity findById(@NotNull UUID id) {
return new Entity(id, "Some name");
}
}
IDE 没有发现任何问题,也没有提供错误。
我尝试通过maven编译项目并得到以下信息:
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 22.602 s
[INFO] Finished at: 2024-07-06T12:48:51+04:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.11.0:compile (compile) on project kotlin-interpolation: Compilation failure: Compilation failure:
[ERROR] .../kotlin-interpolation/src/main/kotlin/com/example/JavaImpl.java:[9,8] com.example.JavaImpl is not abstract and does not override abstract method findById-WQTzO-4(java.util.UUID) in org.example.com.example.KotlinInterface
[ERROR] .../kotlin-interpolation/src/main/kotlin/com/example/JavaImpl.java:[11,5] method does not override or implement a method from a supertype
[ERROR] .../kotlin-interpolation/src/main/kotlin/com/example/JavaImpl.java:[13,16] Entity(java.util.UUID,java.lang.String) has private access in org.example.com.example.Entity
[ERROR] -> [Help 1]
您可以在这里找到重现问题的项目:github:Kotlin-插值问题
有没有办法以正确的方式避免此类问题? (不能选择创建桥接器、适配器或代理)
鼓励提供代码/配置示例。
您需要使用
@NonNull
来注释 id
参数,而不是 NotNull
。否则将无法兼容 Kotlin 的接口签名。