在 kotlin 中返回不同类型的对象 [英] Return different types of Object in kotlin
问题描述
我正在使用一种返回不同类型对象的方法,我使用了 Any 类型返回,但是有没有更好的选择来实现这一点?这是我的方法:
I am working with a method which returns different types of objects, I have used the Any type return, but is there a better option to achieve this? This is my method:
override fun getNavItemById(dCSServiceContext: DCSServiceContext): Observable<Any> {
return scribeProvider.getNavItemById(dCSServiceContext).map { navItem ->
scribePresenter.presentNativeItem(navItem)
}.toObservable()
}
在我对返回的对象进行转换后,使用 when 运算符,我正在做这样的事情:
After I am doing a casting of the returned object, using the when operator, and I am doing something like this:
when (item) {
is NavItem -> {
if (parentItem.hasChildren) {
parentItem.items?.add(item)
recursiveItem = item
}
}
is Image -> {
if (parentItem.hasImages) {
parentItem.image = Image(item.image, item.selectedImage)
recursiveItem = parentItem
}
}
}
我的另一个疑问是如何使用这种方法并用另一种方法提取这种类型的对象.
And my other doubt is how can I use this method and extract this type of object with another approach.
谢谢!!!
推荐答案
你需要的是一个 co-product 类型,就像许多流行的 FP 库中的 Either
数据类型一样,对于 Kotlin,Arrow-kt 已经提供,但同样可以使用密封类
来完成.
What you need is a co-product type, like the Either
data type found in many popular FP libraries, for Kotlin, Arrow-kt already provide it, but the same can be done using sealed classes
too.
示例(密封类)
sealed class Result {
data class A(val value: Int) : Result()
data class B(val value: String) : Result()
}
fun intOrString(number: Int): Result =
if (number%2 == 0) Result.A(number)
else Result.B("~$number~")
fun main(args: Array<String>) {
(1..10).map(::intOrString).forEach(::println)
}
输出
B(value=~1~)
A(value=2)
B(value=~3~)
A(value=4)
B(value=~5~)
A(value=6)
B(value=~7~)
A(value=8)
B(value=~9~)
A(value=10)
示例(任一数据类型)
fun intOrString(number: Int): Either<Int, String> =
if (number%2 == 0) Left(number)
else Right("~$number~")
fun main(args: Array<String>) {
(1..10).map(::intOrString).forEach(::println)
}
输出
Right(b=~1~)
Left(a=2)
Right(b=~3~)
Left(a=4)
Right(b=~5~)
Left(a=6)
Right(b=~7~)
Left(a=8)
Right(b=~9~)
Left(a=10)
这篇关于在 kotlin 中返回不同类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!