Sepideh Abadpour
Sepideh Abadpour

Reputation: 2598

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

I have the following piece of code:

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

I want the values horizontalDistance: Double, heightDifference: Double, slopePercent: Double, slopeDistance: Double and g12DMS: DMSAngle to be returned from the function. How can I do this?

I also need a comprehensive guide in order to understand how to return multiple values (with or without different types) from a function in 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, but it seems that most of these are used to return primitive data types not data classes and since I'm a beginner to Kotlin, I'm a bit confused. Would you please provide me a comprehensive explanation about returning multiple values in Kotlin or introduce me a book/ any other comprehensive text about this issue?

Upvotes: 3

Views: 1967

Answers (1)

Todd
Todd

Reputation: 31700

Kotlin doesn't support multiple return types. The idiomatic way to do this is to declare a class or a data class (I'm just making up a name, change to suit):

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

And at the end of your function:

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

Upvotes: 5

Related Questions