Skip to content
DeveloperMemos

Using Kotlin's repeat and Mock Data

Kotlin, Programming, Mock Data1 min read

The repeat function in Kotlin allows you to execute a block of code a specified number of times. It's particularly useful for repetitive tasks or when you need to perform an action iteratively.

Here's the basic syntax of the repeat function:

1repeat(count) {
2 // Your code here
3}
  • count: The number of times you want the block of code to execute.

Example: Generating a List of Random Integers

Let's say you want to create a list of 10 random integers. You can use repeat to achieve this:

1val randomIntList = mutableListOf<Int>()
2
3repeat(10) {
4 val randomInt = (0..100).random()
5 randomIntList.add(randomInt)
6}
7
8println(randomIntList)

In this example:

  • We create an empty mutable list called randomIntList.
  • The repeat(10) block generates 10 random integers between 0 and 100 and adds them to the list.
  • Finally, we print the contents of randomIntList.

Filling a List with Mock Data

When writing unit tests, you often need mock data to simulate real-world scenarios. Let's create a simple example where we mock a list of user names:

1data class User(val id: Int, val name: String)
2
3fun createMockUsers(count: Int): List<User> {
4 val mockUsers = mutableListOf<User>()
5
6 repeat(count) { index ->
7 val userId = index + 1
8 val userName = "User $userId"
9 mockUsers.add(User(userId, userName))
10 }
11
12 return mockUsers
13}
14
15fun main() {
16 val mockUserList = createMockUsers(5)
17 mockUserList.forEach { println(it) }
18}

In this example:

  • We define a User data class with an id and a name.
  • The createMockUsers function generates a list of mock users with unique IDs and names like "User 1," "User 2," etc.
  • Adjust the count parameter to create as many mock users as needed.

Remember to adapt the mock data creation logic to your specific use case. You can use repeat to generate any type of mock data, whether it's user profiles, product information, or other entities.

Happy coding! 🎉