How to use a variable with space in Kotlin data class

Viewed 117

Context: I am passing the x value, y value and z value from an Arduino accelerometer sensor to Firebase Realtime Database. The way Arduino passes the values to real-time database is shown below (X Axis, Y Axis, Z Axis). I could not change the way it passes the variable name to Firebase. I want it to be like x_axis, y_axis, and so on.

***FIREBASE REALTIME DATABASE

"data": {
        "data1": {
          "X Axis": 0.78,
          "Y Axis": 0.91,
          "Z Axis": 0.07
        },
        "data2": {
          "X Axis": 0.23,
          "Y Axis": 0.21,
          "Z Axis": 0.43
        }
      }

My Kotlin data class to accommodate this is shown below (using backtick to define the variable and identifier suppress at top of the file + turned off the Identifier linting in IDE setting):

@file:Suppress("IllegalIdentifier")
package com.example.projectxyz.model.user_list

data class DataMeasured(
    val `X Axis`: Double = 0.00,
    val `Y Axis`: Double = 0.00,
    val `Z Axis`: Double = 0.00,
)

This is the error I am getting when tried to build the app:

> Task :app:dexBuilderDebug FAILED
AGPBI: {"kind":"error","text":"com.android.tools.r8.internal.XI0: Space characters in SimpleName 'X Axis' are not allowed prior to DEX version 040","sources":[{"file":"C:\\01PrasanthCodes\\ProjectsPras\\1AndroidDevelopment\\Harinivas\\app\\build\\tmp\\kotlin-classes\\debug\\com\\example\\projectxyz\\model\\user_list\\DataMeasured.class"}],"tool":"D8"}
AGPBI: {"kind":"error","text":"com.android.tools.r8.internal.XI0: Space characters in SimpleName 'X Axis' are not allowed prior to DEX version 040","sources":[{"file":"C:\\01PrasanthCodes\\ProjectsPras\\1AndroidDevelopment\\Harinivas\\app\\build\\tmp\\kotlin-classes\\debug\\com\\example\\projectxyz\\model\\user_list\\DataMeasured.class"}],"tool":"D8"}

Is there any way for me to overcome this issue? Thank you so much

1 Answers

You can define your data class like this to fetch the data from firebase and name your variables as you like:

data class DataMeasured (
    @PropertyName("X Axis") val x_axis: Double = 0.00,
    @PropertyName("Y Axis") val y_axis: Double = 0.00,
    @PropertyName("Z Axis") val z_axis`: Double = 0.00
)

If there's a problem with serialization, that might be because of the getters and setters generated by the IDE, try reinforcing them with @get and @set annotations:

data class DataMeasured (
    @set:PropertyName("X Axis") 
    @get:PropertyName("X Axis")
    var x_axis: Double = 0.00,
    @set:PropertyName("Y Axis") 
    @get:PropertyName("Y Axis")
    var y_axis: Double = 0.00,
    @set:PropertyName("Z Axis") 
    @get:PropertyName("Z Axis")
    var z_axis`: Double = 0.00
)
Related