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

How to return multiple values with different types (one of them a data class) from a function in Kotlin?

我有如下一段代码:

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)
}

我希望从函数中 return 编辑值 horizontalDistance: DoubleheightDifference: DoubleslopePercent: DoubleslopeDistance: Doubleg12DMS: DMSAngle。我该怎么做?

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

Kotlin 不支持多个 return 类型。这样做的惯用方法是声明一个 class 或一个 data 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
)