我有以下代码:
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: Double
和 g12DMS: DMSAngle
从函数中返回。我该怎么做?
我还需要一份全面的指南,以便了解如何从 Kotlin 中的函数返回多个值(具有或不具有不同类型)。 I have read about this听说过Pair
, Triple
, Array<Any>
, List
, interface
, sealed class
或 using the trick of creating data class to return and then destructing , 但似乎其中大部分用于返回 primitive data types
不是data classes
由于我是 Kotlin 的初学者,所以我有点困惑。您能否为我提供有关在 Kotlin 中返回多个值的全面解释,或者给我介绍一本书/任何其他有关此问题的全面文本?
最佳答案
Kotlin 不支持多种返回类型。执行此操作的惯用方法是声明一个 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
)
关于function - 如何从 Kotlin 中的函数返回具有不同类型(其中一个是数据类)的多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68941286/