解决 Kotlin 中的意外覆盖错误 [英] Resolving Accidental Override errors in Kotlin
问题描述
我最近开始使用 Kotlin 过期,并使用 Kotlin 启动了一个 Spring Boot 宠物项目.
I've recently started expirementing with Kotlin and started a Spring Boot pet project using Kotlin.
我正在尝试将自定义用户域对象集成到 Spring Security,因此想要实现 UserDetails 界面.
I'm trying to integrate a custom User domain object to Spring Security and thus want to implement the UserDetails inteface.
鉴于我的域用户对象如下:
Given my domain User object below:
import org.springframework.data.annotation.Id as DocumentId
import org.springframework.data.mongodb.core.mapping.Document
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.AuthorityUtils
import org.springframework.security.core.userdetails.UserDetails
@Document
data class User(@DocumentId val id: String? = null,
val username: String = "",
val password: String = "",
val email: String = "",
val name: String? = null,
val surname: String? = null) : UserDetails {
override fun isCredentialsNonExpired(): Boolean = true
override fun isAccountNonExpired(): Boolean = true
override fun isAccountNonLocked(): Boolean = true
override fun getAuthorities(): MutableCollection<out GrantedAuthority> = AuthorityUtils.createAuthorityList("USER")
override fun isEnabled(): Boolean = true
}
我收到以下错误:
意外覆盖:以下声明具有相同的JVM签名 (getUsername()Ljava/lang/String;): public final fun <;get-username>(): Kotlin.String, public abstract fun getUsername(): Kotlin.String!
Accidental override: The following declarations have the same JVM signature (getUsername()Ljava/lang/String;): public final fun < get-username>(): Kotlin.String, public abstract fun getUsername(): Kotlin.String!
意外覆盖:以下声明具有相同的JVM签名 (getPassword()Ljava/lang/String;): public final fun <get-password>(): Kotlin.String, public abstract fun getPassword(): Kotlin.String!
Accidental override: The following declarations have the same JVM signature (getPassword()Ljava/lang/String;): public final fun < get-password>(): Kotlin.String, public abstract fun getPassword(): Kotlin.String!
因为我的 User 类已经有一个方法 getUsername(): Kotlin.String 也实现了方法 getUsername(): Kotlin.String!?
Since my User class already has a method getUsername(): Kotlin.String also implement the method getUsername(): Kotlin.String! ?
除了使用 @JvmName 在属性的 getter 和 setter 上?
How am I supposed to resolve such an error, other than using the @JvmName on the property's getter and setter?
推荐答案
这里的问题是,从 Kotlin 的角度来看,属性 getter 不可能覆盖来自超类型的函数.要解决此问题,您可以通过将属性设为 private
并手动从超类型实现所需的方法来阻止编译器生成 getter,例如:
The problem here is that it's impossible for a property getter to override a function from a supertype, from Kotlin's point of view. To workaround it, you can prevent the compiler from generating getters by making your properties private
and implement required methods from supertypes manually, for example:
data class User(
private val username: String = ""
...
): UserDetails {
override fun getUsername() = username
...
}
这篇关于解决 Kotlin 中的意外覆盖错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!