-3

I am looking to try to us this piece of code which thanks to Azimuth reading changes to opposite when user holds the phone upright I need to use this code to experiment in Java however i am unsure of how to translate the code below in to Java:

    override fun onSensorChanged(event: SensorEvent) {
        if (event.sensor.type != Sensor.TYPE_ROTATION_VECTOR) return
        SensorManager.getRotationMatrixFromVector(rotationMatrix, event.values)
        val (matrixColumn, sense) = when (val rotation = 
                activity.windowManager.defaultDisplay.rotation
        ) {
            Surface.ROTATION_0 -> Pair(0, 1)
            Surface.ROTATION_90 -> Pair(1, -1)
            Surface.ROTATION_180 -> Pair(0, -1)
            Surface.ROTATION_270 -> Pair(1, 1)
            else -> error("Invalid screen rotation value: $rotation")
        }
        val x = sense * rotationMatrix[matrixColumn]
        val y = sense * rotationMatrix[matrixColumn + 3]
        azimuthChanged(-atan2(y, x))
    }

If any one could help understand and translate this to Java that would be a big help, it looks fairly simple but i am unsure on the syntax of these lines:

val (matrixColumn, sense) = when (val rotation = 
                activity.windowManager.defaultDisplay.rotation
        ) {
            Surface.ROTATION_0 -> Pair(0, 1)
            Surface.ROTATION_90 -> Pair(1, -1)
            Surface.ROTATION_180 -> Pair(0, -1)
            Surface.ROTATION_270 -> Pair(1, 1)
            else -> error("Invalid screen rotation value: $rotation")
        }

Thanks if you can help.

ProjH
  • 13
  • 4
  • first google result for `Kotlin when` is [this, the actuald docs](https://kotlinlang.org/docs/reference/control-flow.html#when-expression). Stating: `The when expression replaces the switch statement in C-like languages`. So ... switch it to a `switch`. – AlexT Feb 09 '21 at 22:00

1 Answers1

1

This is using a destructuring declaration, which isn't available in Java, so instead you have to declare two variables and then assign them in a switch statement, which is analogous to a Kotlin when statement.

int matrixColumn;
int sense;
switch(getActivity().getWindowManager().getDefaultDisplay.getRotation()) {
    case Surface.ROTATION_0:
        matrixColumn = 0;
        sense = 1;
        break;
    case Surface.ROTATION_90:
        matrixColumn = 1;
        sense = -1;
        break;
    case Surface.ROTATION_180:
        matrixColumn = 0;
        sense = -1;
        break;
    default: // Surface.ROTATION_270:
        matrixColumn = 1;
        sense = 1;
        break;
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154