我正在try 添加将一些域对象转换为javax.persistence.criteria.Predicate的动态谓词,但是在泛型方法中正确指定类型时遇到了问题.下面是一段简化的代码,或多或少地呈现了我必须维护的方法契约.我的意思是,pathvalue都是以某种方式计算出来的.

enum class Operator { EQUAL, NOT_EQUAL, GREATER_THAN_OR_EQUAL, LESS_THAN_OR_EQUAL, GREATER_THAN, LESS_THAN, }

inline fun <T> buildPredicate(
            root: Root<*>,
            builder: CriteriaBuilder,
            operator: Operator,
            pathSupplier: () -> Path<T>,
            valueSupplier: () -> T
        ) {
            val path = pathSupplier()
            val value = valueSupplier()
            when (operator) {
                EQUAL -> builder.equal(path, value)              // ok
                GREATER_THAN -> builder.greaterThan(path, value) // this wont compile though
                else -> throw IllegalArgumentException()
            }
        }

在标记线上显示

None of the following functions can be called with the arguments supplied.

不过,我的目标是一个定义

<Y extends Comparable<? super Y>> Predicate greaterThan(Expression<? extends Y> x, Y y);

Is this even doable?

作为附注,我可以添加上面示例中的运行时T将解析为某个enumStringLocalDateTime.

推荐答案

使用where T: Comparable<T>子句提供方法的界限(见下面修改的方法)-更多信息-https://kotlinlang.org/docs/generics.html#type-erasure;

inline fun <T> buildPredicate(
    root: Root<*>,
    builder: CriteriaBuilder,
    operator: Operator,
    pathSupplier: () -> Path<T>,
    valueSupplier: () -> T
) where T: Comparable<T>{
    val path = pathSupplier()
    val value = valueSupplier()
    when (operator) {
        Operator.EQUAL -> builder.equal(path, value)              // ok
        Operator.GREATER_THAN -> builder.greaterThan(path, value) // this compiles
        else -> throw IllegalArgumentException()
    }
}

Kotlin相关问答推荐

UByte范围. Min_UTE.. UByte.MAX_UTE不符合预期

Kotlin—列出具有不同T的列表之间的操作'

Regex(Kotlin)仅匹配句子末尾的句号,而忽略中间的句号,如缩写

我如何测试一个可组合组件没有显示,但如果它不存在也接受?

jOOQ Kotlin Coroutines - Select all and exists查询

Kotlin 中命名构造函数的惯用方式

在 Kotlin 中实现并输入 Either

Kotlin supervisorScope 即使包裹在 try catch 中也会失败

可组合项在返回后返回时组合导航句柄

使用 LazyListScope 嵌套可组合项

如何从 kotlin 中的数据类访问 val?

Kotlin 使用迭代索引过滤 lambda 数组

参考 Kotlin 中的 Java 接口静态字段

kotlin-bom 库是做什么的?

main函数和常规函数有什么区别?

在 suspendCoroutine 块中调用挂起函数的适当方法是什么?

如何在伴随对象中使用泛型

在 Kotlin 中声明 Byte 会出现编译时错误The integer literal does not conform to the expected type Byte

Android room DAO 接口不适用于继承

任务':app:kaptDebugKotlin'的Kotlin执行失败