function - 如何从 Kotlin 中的函数返回具有不同类型(其中一个是数据类)的多个值?

标签 function kotlin return return-value return-type

我有以下代码:

data class DMSAngle(var degree: Double, var minute: Double, var second: Double)

fun coordinateInverseCalculation(point1: Point3D, point2: Point3D){

    val horizontalDistance = sqrt(
        (point2.easting - point1.easting).pow(2.0) +
            (point2.northing - point1.northing).pow(2.0)
    )

    val heightDifference = point2.height - point1.height

    val slopePercent = (heightDifference / horizontalDistance) * 100

    val slopeDistance = sqrt(
        (point2.easting - point1.easting).pow(2.0) +
                (point2.northing - point1.northing).pow(2.0) +
                (point2.height - point1.height).pow(2.0)
    )

    val point12D = Point(easting = point1.easting, northing = point1.northing)
    val point22D = Point(easting = point2.easting, northing = point2.northing)
    val g12 = gizement(point12D, point22D)
    val g12DMS = decimalDegreesToDMS(g12)
}

我想要值 horizontalDistance: Double , heightDifference: Double , slopePercent: Double , slopeDistance: Doubleg12DMS: DMSAngle从函数中返回。我该怎么做?

我还需要一份全面的指南,以便了解如何从 Kotlin 中的函数返回多个值(具有或不具有不同类型)。 I have read about this听说过Pair , Triple , Array<Any> , List , interface , sealed classusing the trick of creating data class to return and then destructing , 但似乎其中大部分用于返回 primitive data types不是data classes由于我是 Kotlin 的初学者,所以我有点困惑。您能否为我提供有关在 Kotlin 中返回多个值的全面解释,或者给我介绍一本书/任何其他有关此问题的全面文本?

最佳答案

Kotlin 不支持多种返回类型。执行此操作的惯用方法是声明一个 classdata class(我只是在编一个名字,更改以适应):

data class CoordinateInverse(
    val horizontalDistance: Double, 
    val heightDifference: Double, 
    val slopePercent: Double, 
    val slopeDistance: Double, 
    val g12DMS: DMSAngle
)

在你的函数结束时:

return CoordinateInverse(
    horizontalDistance,
    heightDifference,
    slopePercent,
    slopeDistance,
    g12DMS
)
    
    

关于function - 如何从 Kotlin 中的函数返回具有不同类型(其中一个是数据类)的多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68941286/

相关文章:

java - 尝试在 Java 中返回分数(作为 float )

与 char* 冲突的类型

c++ - 这个递归函数是如何工作的?合并排序两个单链表

c - int 如何等于另一个返回 long int 的函数?

c++ - 为什么要在 C++ 中将智能指针作为函数参数传递?

kotlin - 理解初始化为扩展函数的参数

python - 为什么我的递归函数返回 None?

android - kotlin 按数组列表中属性值的总和分组

Firebase:没有匹配的允许语句

"return"的 C++ 说明