Kotlin: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
No edit summary
Line 38: Line 38:
         mySportsActivity2 = gson.fromJson(reader,SportsActivity::class.java)
         mySportsActivity2 = gson.fromJson(reader,SportsActivity::class.java)
     }
     }
== Range For Loop ==
val myTest = 212
for(i in 0..7)
{
  val myGetValue = IsByteSet(myTest,i)
  val myTest2 = myGetValue
}

Revision as of 22:44, 9 March 2018

Data Class

data class SportsActivity (
       val totalAveragePaceInMinutesPerKilometre: Double,
       val totalAverageSpeedInKilometresPerHour: Double,
       val totalDurationInSeconds: Int,
       val totalAverageDistanceInMetres: Double, 
       var dateOfActivity: Date
)

Reading and Writing to Gson

Given the following

    var mySportsActivity = SportsActivity(
           0.0,
           0.0,
           0,
           0.0,
           Date())
   val gson = Gson()
   val json = gson.toJson(mySportsActivity)
   var filename = "D:\\IAIN\\Output.json";

You can write to a file with

    FileWriter(filename).use {
       writer ->
       val gson = GsonBuilder().setPrettyPrinting().create()
       gson.toJson(mySportsActivity, writer)
    }

And read it back with

    FileReader("D:\\IAIN\\Output.json").use {
       reader ->
       val gson = GsonBuilder().setPrettyPrinting().create()
       mySportsActivity2 = gson.fromJson(reader,SportsActivity::class.java)
    }

Range For Loop

val myTest = 212
for(i in 0..7)
{
  val myGetValue = IsByteSet(myTest,i)
  val myTest2 = myGetValue
}