首页 > 解决方案 > 如何从 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)
}

我希望从函数返回值horizontalDistance: DoubleheightDifference: DoubleslopePercent: Double和。我怎样才能做到这一点?slopeDistance: Doubleg12DMS: DMSAngle

我还需要一份综合指南,以了解如何从 Kotlin 中的函数返回多个值(有或没有不同类型)。我已经阅读过这个并且听说过Pair, Triple, Array<Any>, List, interface,sealed class或者使用创建数据类来返回然后破坏的技巧,但似乎大多数这些都用于不返回primitive data typesdata classes因为我是 Kotlin 的初学者,我有点糊涂了。您能否向我提供有关在 Kotlin 中返回多个值的全面解释,或者向我介绍一本书/有关此问题的任何其他全面文本?

标签: functionkotlinreturnreturn-valuereturn-type

解决方案


Kotlin 不支持多种返回类型。这样做的惯用方法是声明 aclass或 a 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
)
    
    

推荐阅读