Issue
Could someone give me a little pointer on data classes. I'm finding a very steep learning curve with Kotlin, but I'm getting there slowly.
I have a data class of:
data class newGame(
val gamename: String,
val gamedate: String,
val players: List<Player>
) {
data class Player(
val player: String,
val player_id: Int,
val score: Int,
val points: Int
)
}
I can create an instance of the outer (newGame) class, but I'm struggling to get to grips with how I add Players. I thought I could do something like:
var gm: newGame
gm.gamename = GamesList.text.toString()
val p = newGame.Player
p.player = Player1.text.toString()
gm.players.add p
But Android Studio says I need a companion object and I'm not sure how that needs to look
The interface looks like:
interface CreateGame {
@POST("new")
fun addNewGame(
@Query("operation") operation: String,
@Body() newGame: newGame
): Call<gameEvent>
companion object {
fun create(): CreateGame {
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BaseURL)
.build()
return retrofit.create(CreateGame::class.java)
}
}
I get how the companion object create() creates the instance of the game, but I can't figure out what I need to write so that I can add players to the inner class.
Could someone give me a pointer please?
Solution
I can create an instance of the outer (newGame) class, but I'm struggling to get to grips with how I add Players. I thought I could do something like:
Well, first understood the terms val and var. The property gamename is val which means its read-only, to write it you have to make it as var, same goes to all other properties. and players should be mutableListOf or ArrayList<> type so you can modify it later. List is immutable, which means you can't add after initialization.
data class newGame(
var gamename: String,
var gamedate: String,
var players: ArrayList<Player>
)
data class Player(
var player: String,
var player_id: Int,
var score: Int,
var points: Int
)
Now In your case, you need to add a secondary constructor OR initialize all properties while declaring as below
data class newGame(
var gamename: String? = null,
var gamedate: String? = null,
var players: ArrayList<Player> = ArrayList()
)
data class Player(
var player: String?=null,
var player_id: Int?=null,
var score: Int?=null,
var points: Int?=0
)
In main class
var gm: newGame = newGame()
gm.gamename = "GamesList.text.toString()"
val p = Player()
p.player = "Player1.text.toString()"
gm.players.add(p)
Answered By - Shoaib Khalid
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.