从Kotlin箭头的任何一种类型中提取值并将其分配给const

时间:2020-05-12 20:41:49

标签: kotlin arrow-kt

这将是一个基本问题,但我找不到解决方案。我需要从任一类型下面的右侧值中初始化一个常量。

val test: Either<String, Int> = 1.right()

我尝试了以下类似方法,但是它缩小了常量的范围。

when(test) {
        is Either.Right -> {val get:Int = test.b}
        is Either.Left -> println(test.a)
    }

我希望get的范围超出when语句的范围。有什么方法可以做到这一点,或者不是为此目的而制作了Arrow Either?

1 个答案:

答案 0 :(得分:5)

重要的问题是:如果Either为Left,该怎么办。在本示例中,它是在使用位置附近创建的,因此对于开发人员而言,这是显而易见的。但是对于编译器而言,Either内部可以是IntString

您可以使用fold等提取值:

val x = test.fold({ 0 }, {it}) // provide 0 as default in case the Either was a `Left`
// x = 1

另一个选项是getOrElse

val test = 1.right()
val x = test.getOrElse { 42 } // again, default in case it was a `Left`
// x = 42

您也可以使用它而无需打开它:

val test = 1.right()
val testPlus10 = test.map { it + 10 } // adds 10 to `test` if it is `Right`, does nothing otherwise
val x = testPlus10.getOrElse { 0 } // unwrap by providing a default value
// x = 11

有关更多示例,请检查official docs

推荐阅读:How do I get the value out of my Monad