function - 如何从 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: Double
、heightDifference: Double
、slopePercent: Double
和。我怎样才能做到这一点?slopeDistance: Double
g12DMS: DMSAngle
我还需要一份综合指南,以了解如何从 Kotlin 中的函数返回多个值(有或没有不同类型)。我已经阅读过这个并且听说过Pair
, Triple
, Array<Any>
, List
, interface
,sealed class
或者使用创建数据类来返回然后破坏的技巧,但似乎大多数这些都用于不返回primitive data types
,data classes
因为我是 Kotlin 的初学者,我有点糊涂了。您能否向我提供有关在 Kotlin 中返回多个值的全面解释,或者向我介绍一本书/有关此问题的任何其他全面文本?
解决方案
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
)
推荐阅读
- java - Java 使用 SimpleDateFormat 解析日期和时间
- java - 如何从 AccessibilityNodeInfo 中的所有子节点获取文本
- android - 显示 AutoCompleteTextView 描述搜索 id
- mysql - MySQL 为 null 不返回任何内容
- c++ - C++ 中有整数 fmod 的函数吗?
- qooxdoo - 如何关闭所有分支
- c++ - 在单个 Raspberry-Pi 上使用 MPI
- python - 将列表作为查询参数传递
- javascript - 如何检查一个对象的键和深键是否相等,类似于lodash的isEqual?
- c++ - 将输出定向到 C++ 中的 .txt 文件