org.springframework.core.convert.converter.Converter<S, T>给出错误:Null 不能是非 null 类型的值



我尝试实现弹簧转换器,但是我在单元测试中遇到了错误:

Kotlin: Null can not be a value of a non-null type TodoItem

如果我尝试更改

的转换方法签名
override fun convert(source: TodoItem): GetTodoItemDto?

to

override fun convert(source: TodoItem?): GetTodoItemDto?

将null传递到方法我还有其他错误:

Error:(10, 1) Kotlin: Class 'TodoItemToGetTodoItemDto' is not abstract and does not implement abstract member @Nullable public abstract fun convert(p0: TodoItem): GetTodoItemDto? defined in org.springframework.core.convert.converter.Converter
Error:(14, 5) Kotlin: 'convert' overrides nothing

代码样本:

todoitemtogettodoitemdto.kt

package com.example.todo.converters
import com.example.todo.dtos.todo.GetTodoItemDto
import com.example.todo.model.TodoItem
import org.springframework.core.convert.converter.Converter
import org.springframework.lang.Nullable
import org.springframework.stereotype.Component
@Component
class TodoItemToGetTodoItemDto : Converter<TodoItem?, GetTodoItemDto> {
    @Nullable
    @Synchronized
    override fun convert(source: TodoItem): GetTodoItemDto? {
        if(source == null){
            return null
        }
        return GetTodoItemDto(source.id, source.name, source.isComplete)
    }
}

package com.example.todo.converters
import org.junit.Before
import org.junit.Test
import org.junit.Assert.*

class TodoItemToGetTodoItemDtoTest {
    private lateinit var conveter : TodoItemToGetTodoItemDto
    @Before
    fun setUp() {
        conveter = TodoItemToGetTodoItemDto()
    }
    @Test
    fun testNullObject(){
        assertNull(conveter.convert(null))
    }
}

getTodoItemdto.kt

package com.example.todo.dtos.todo
data class GetTodoItemDto(val id: Long, val name: String, val isComplete: Boolean)

todoitem.kt

package com.example.todo.model
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
@Entity
data class TodoItem @JsonCreator constructor(
        @Id
        @GeneratedValue
        @JsonProperty(access = JsonProperty.Access.READ_ONLY)
        var id: Long,
        var name: String,
        var isComplete: Boolean){
    constructor(): this(0, "", false)
    constructor(name:String) : this(0, name, false)
}

您能否向我解释如何使用Kotlin实施?我可能会使用Kotlin做错了什么?

我不认为您要做的是有效的。如果您查看Converter.convert Javadocs,您会发现source函数中的CC_2参数具有以下方式:

@param源源对要转换的源对象,必须是一个实例 {@code s}(从不{@code null} (

因此,它明确地说您永远无法将null传递到convert函数中。

相反,convert函数返回的内容可以为null:

@return转换的对象,必须是{@code t}的实例 (可能{@code null} (

Java代码中的convert方法用@Nullable注释,而Javadocs则说:

...由Kotlin用于推断Spring Api的无效性。

这就是Kotlin的决定是否可以为null(在这种情况下,参数不能,但返回值可以(。

最新更新