如何在 Groovy 代码中使用 Arrow-kt 的 Some()?

How can I use Arrow-kt's Some() in Groovy code?

我正在尝试使用 Groovy 中的 Spock 测试我的 Kotlin 代码,它具有 Arrow-kt 类型。但是,我无法使用 Arrow-kt 的添加项,例如 Some。比如我有一个测试如下:

    @Unroll
    def "add returns #expected for queryRecord #queryRecord"() {
        given:
        def ip = "ip"
        def rule = "rule"

        when:
        def result = unit.add(ip, rule)

        then:
        1 * dynamoDBMapperMock.load(ActionRecord.class, ip) >> queryRecord

        result == expected

        where:
        queryRecord        | expected
        new ActionRecord() | None.INSTANCE
        null               | Some(new ActionInternal("ip"))
    }

虽然第一个数据行成功且没有问题,但第二个数据行失败并出现以下错误:

groovy.lang.MissingMethodException: No signature of method: package.name.EventSpec.Some() is applicable for argument types: (package.name.ActionInternal) values: [ActionInternal(dropletIp=null)] Possible solutions: Mock(), Spy(), Stub(), dump(), Mock(groovy.lang.Closure), Mock(java.lang.Class)

我也试过 .some(),但没有用。显然 Groovy 无法访问 Kotlin 扩展,但 Some 只是一个数据 class[1],所以我不确定为什么我不能在 Groovy.

是的,您可以在 Groovy 中使用 Arrow Datatypes,结果不像 Kotlin 中那样地道,因为该库严重依赖 [=] 中的扩展函数和函数14=]

例子

import arrow.core.Option
import static arrow.core.OptionKt.getOrElse

static main(args){
    println 'What is your name?'
    def name = Option.@Companion.fromNullable(System.in.newReader().readLine())
        .filterNot { it.isEmpty() }
        .map { it.toUpperCase() }

    println("Welcome ${getOrElse(name) { 'Anonymous' }}")
}

输出

'Welcome JOHN' (or 'Welcome Anonymous' if the provided name is null or empty) 

如您所见,为了能够使用getOrElse扩展函数,我们需要将其作为静态方法导入

提示

不要直接使用Some,除非你绝对确定该值不是null,否则,你应该依靠Option.fromNullable安全地将值提升到[=19] =] 上下文(即创建 SomeNone 取决于值是否为 null