Data classes

When building apps, most of the time we require classes whose only function is to store data. In Java, we usually use a POJO for this. In Kotlin, there's a special class for that known as the data class

Let's say we want to keep a scoreboard for our TicTacToe game. How will we store the data for each game session?

In Java, we'll create a POJO that will store data about the game session (the board at the end of the game and the winner of that game):

public class Game {

private char[][] gameBoard;
private char winner;

public Game(char[][] gameBoard, char winner) {
setGameBoard(gameBoard);
setWinner(winner);
}

public char[][] getGameBoard() {
return gameBoard;
}

public void setGameBoard(char[][] gameBoard) {
this.gameBoard = gameBoard;
}

public char getWinner() {
return winner;
}

public void setWinner(char winner) {
this.winner = winner;
}
}

In Kotlin, this is greatly simplified to:

data class Game(var gameBoard: Array<CharArray>, var winner: Char)

The previous single line of code does the same thing as the previous 26 lines of Java code. It declares a Game class that takes two parameters in its primary constructor. As stated earlier, the getters and setters are not needed. 

The data class in Kotlin also comes with a number of other methods:

  • equals()/hashCode() pair
  • toString()
  • copy()

If you've ever written any Java code, you should be familiar with equals(), hashCode(), and toString(). Let's go ahead and discuss copy().

The copy() method comes in handy when you want to create a copy of an object but with part of its data altered, for example:

data class Student(var name: String, var classRoomNo: Int, var studentId: Int) // 1

var anna = Student("Anna", 5, 1) // 2
var joseph = anna.copy("Joseph", studentId = 2) // 3

In the preceding code snippet:

  1. We declare a data class called Student. It takes three parameters in its primary constructor: name, classRoomNo, and studentId.
  2. The anna variable is an instance of the Student with the following properties: name:AnnaclassRoomNo:5, and studentId:1.
  3. The variable joseph is created from copying anna and changing two of the properties—name and studentId.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset