Digital Library

Kotlin Exercises (Marcin Moskała)(Z-Library)

Share E-Book

Kotlin Exercises (Marcin Moskała)(Z-Library)

Author

Rating No ratings yet

Log in to rate

Programming Language
Language English

No Description

Format PDF
Size 1.7 MB
8
Views
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
Kotlin Exercises Marcin Moskała This book is available at http://leanpub.com/kotlin_exercises This version was published on 2024-10-10 © 2024 Marcin Moskała
Page 3
Contents Introduction 1 Kotlin Essentials exercises 2 Exercise: Your first program 3 Exercise: Basic values operations 4 Exercise: Using when 5 Exercise: Pretty time display 6 Exercise: Person details display 7 Exercise: Range Operations 8 Exercise: User Information Processor 10 Exercise: Implementing the Product class 12 Exercise: GUI View Hierarchy Simulation 14 Exercise: Data class practice 16 Exercise: Pizza factory 17 Exercise: Catching exceptions 18 Exercise: Days of the week enum 20 Exercise: Conversion and measurement unit creation 21 Exercise: Inventory management 23 Exercise: Money operations 26 Exercise: The closest supertype of types 27 Exercise: Stock 28 Final Project: Workout manager 29 Functional Kotlin exercises 32 Exercise: Function types and literals 33 Exercise: Observable value 35 Exercise: Inferred function types 36 Exercise: Function references 37 Exercise: Inline functions 38 Exercise: Implement map 39 Exercise: Optimize collection processing 40 Exercise: Adding element at position 41
Page 4
CONTENTS Exercise: Implement shop functions 42 Exercise: Prime access list 43 Exercise: Top articles 45 Exercise: Refactor collection processing 46 Exercise: Passing students list 48 Exercise: Best students list 49 Exercise: Functional Quick Sort 50 Exercise: Powerset 51 Exercise: All possible partitions of a set 52 Exercise: Understanding sequences 53 Exercise: HTML table DSL 54 Exercise: Creating user table row 56 Exercise: Using scope functions 57 Exercise: orThrow 59 Exercise: Logger 60 Final Project: UserService 63 Kotlin Coroutines exercises 65 Exercise: Factorial sequence 66 Exercise: Prime numbers sequence 67 Exercise: Callback function wrappers 68 Exercise: Continuation storage 69 Exercise: What is stored by a continuation? 70 Exercise: UserDetailsRepository 71 Exercise: BestStudentUseCase 72 Exercise: CommentService 73 Exercise: mapAsync 74 Exercise: Understanding context propagation 75 Exercise: CounterContext 76 Exercise: Using dispatchers 77 Exercise: DiscNewsRepository 79 Exercise: Experiments with dispatchers 80 Exercise: Correct mistakes with cancellation 82 Exercise: NotificationSender 84 Exercise: BaseViewModel 85 Exercise: UserDownloader 86 Exercise: CompanyDetailsRepository 87 Exercise: CancellingRefresher 89 Exercise: Suspended lazy 90 Exercise: mapAsync with concurrency limit 91 Exercise: Test UserDetailsRepository 92 Exercise: Testing mapAsync 95 Exercise: Testing the NotificationSender class 97
Page 5
CONTENTS Exercise: Testing a View Model 98 Exercise: UserRefresher 99 Exercise: Cafeteria simulation 100 Exercise: raceOf 101 Exercise: Flow utils 102 Exercise: All users flow 103 Exercise: distinct 104 Exercise: TemperatureService 105 Exercise: NewsViewModel 106 Exercise: ProductService 108 Exercise: Flow Kata 109 Exercise: MessageService 110 Exercise: Update ProductService 112 Exercise: Update TemperatureService 113 Exercise: LocationService 114 Exercise: PriceService 115 Exercise: NewsViewModel using stateIn 116 Exercise: Flow testing 117 Advanced Kotlin exercises 118 Exercise: Usage of generic types 119 Exercise: Generic Response 120 Exercise: Generic Consumer 121 Exercise: ApplicationScope 122 Exercise: Lateinit delegate 123 Exercise: Blog Post Properties 124 Exercise: Mutable lazy delegate 126 Exercise: Coroutine time measurement 127 Exercise: Adjust Kotlin for Java usage 129 Exercise: Multiplatform LocalDateTime 131 Exercise: Migrating a Kotlin/JVM project to KMP 132 Exercise: Function caller 134 Exercise: Object serialization to JSON 136 Exercise: Object serialization to XML 139 Exercise: DSL-based dependency injection library 143 Exercise: Mocking library 145 Exercise: Annotation Processing execution measurement wrapper 147 Exercise: KSP execution measurement wrapper 151 Effective Kotlin exercises 154 Exercise: A mutability problem 155 Exercise: Flow with history 156
Page 6
CONTENTS Exercise: Correct InMemoryUserRepository 157 Exercise: Chunking a flow 158 Exercise: Specify expectations 159 Exercise: Unit testing 161 Exercise: Unit testing using mocks 162 Exercise: Composition vs inheritance 163 Exercise: Make DeckConnector comparable 164 Exercise: Correct EventListenerRegistry 165 Exercise: Market data processing optimization 166 Exercise: Prime access list 172 Exercise: Crime analysis 174 Exercise solutions 175 Solution: Basic values operations 176 Solution: Using when 177 Solution: Pretty time display 178 Solution: Person details display 181 Solution: Range Operations 183 Solution: User Information Processor 185 Solution: Implementing the Product class 186 Solution: GUI View Hierarchy Simulation 187 Solution: Data class practice 188 Solution: Pizza factory 189 Solution: Catching exceptions 190 Solution: Days of the week enum 191 Solution: Conversion and measurement unit creation 192 Solution: Inventory management 193 Solution: Money operations 195 Solution: The closest supertype of types 196 Solution: Stock 197 Solution: Workout manager 198 Solution: Function types and literals 201 Solution: Observable value 203 Solution: Inferred function types 204 Solution: Function references 205 Solution: Inline functions 207 Solution: Implement map 208 Solution: Optimize collection processing 209 Solution: Adding element at position 210 Solution: Implement shop functions 211 Solution: Prime access list 212 Solution: Top articles 214 Solution: Refactor collection processing 215 Solution: Passing students list 216 Solution: Best students list 217
Page 7
CONTENTS Solution: Functional Quick Sort 218 Solution: Powerset 219 Solution: All possible partitions of a set 220 Solution: Understanding sequences 221 Solution: HTML table DSL 222 Solution: Creating user table row 223 Solution: Using scope functions 224 Solution: orThrow 225 Solution: Logger 226 Solution: UserService 227 Solution: Factorial sequence 230 Solution: Prime numbers sequence 231 Solution: Callback function wrappers 232 Solution: Continuation storage 233 Solution: What is stored by a continuation? 234 Solution: UserDetailsRepository 235 Solution: BestStudentUseCase 237 Solution: CommentService 238 Solution: mapAsync 241 Solution: Understanding context propagation 242 Solution: CounterContext 243 Solution: Using dispatchers 244 Solution: DiscNewsRepository 245 Solution: Experiments with dispatchers 246 Solution: Correct mistakes with cancellation 247 Solution: NotificationSender 250 Solution: BaseViewModel 251 Solution: UserDownloader 252 Solution: CompanyDetailsRepository 254 Solution: CancellingRefresher 262 Solution: Suspended lazy 264 Solution: mapAsync with concurrency limit 265 Solution: Test UserDetailsRepository 266 Solution: Testing mapAsync 268 Solution: Testing the NotificationSender class 271 Solution: UserRefresher 274 Solution: Cafeteria simulation 275 Solution: raceOf 276 Solution: Flow utils 277 Solution: All users flow 278 Solution: distinct 279 Solution: TemperatureService 280 Solution: NewsViewModel 281 Solution: ProductService 282 Solution: Flow Kata 284
Page 8
Solution: MessageService 286 Solution: Update ProductService 287 Solution: Update TemperatureService 288 Solution: LocationService 289 Solution: PriceService 291 Solution: NewsViewModel using stateIn 292 Solution: Usage of generic types 293 Solution: Generic Response 294 Solution: Generic Consumer 295 Solution: ApplicationScope 296 Solution: Lateinit delegate 297 Solution: Blog Post Properties 300 Solution: Mutable lazy delegate 301 Solution: Coroutine time measurement 302 Solution: Adjust Kotlin for Java usage 303 Solution: Multiplatform LocalDateTime 304 Solution: Migrating a Kotlin/JVM project to KMP 305 Solution: Function caller 307 Solution: Object serialization to JSON 308 Solution: Object serialization to XML 310 Solution: DSL-based dependency injection library 312 Solution: Mocking library 314 Solution: Annotation Processing execution measurement wrapper 316 Solution: KSP execution measurement wrapper 320 Solution: A mutability problem 325 Solution: Flow with history 326 Solution: Correct InMemoryUserRepository 327 Solution: Chunking a flow 330 Solution: Specify expectations 331 Solution: Make DeckConnector comparable 332 Solution: Correct EventListenerRegistry 333 Solution: Market data processing optimization 335 Solution: Crime analysis 342
Page 9
Introduction This is not a standard book, but rather a collection of exercises that I am using when I am teaching Kotlin. I collected them all into one place, to make them easier to use. Most of those exercises are also included in the following books: • Kotlin Essentials • Functional Kotlin • Kotlin Coroutines: Deep Dive • Advanced Kotlin • Effective Kotlin: Best Practices They include all the knowledge needed to solve them. If you want to learn Kotlin, I recommend you to read them. Though if you are only interested in solving exercises, feel free to use those presented in this book.
Page 10
Kotlin Essentials exercises This is a collection of exercises that were designed to practice the knowledge presented in the Kotlin Essentials book. They are not very difficult, but they will help you to learn and practice some essential knowledge. Some might seem a bit boring, but practicing basic knowledge in separation is sometimes like that. Keep in mind that soon this knowledge will be used to do things that are much more interesting.
Page 11
3 Exercise: Your first program Your task is to create a program that will print “Hello, World” to the console and then check what was the code compiled to on JVM. 1. Install IntelliJ IDEA if you do not have it yet. 2. Create a new Kotlin project. 3. Create a new Kotlin file. 4. Create a main function using Live Template “main”. 5. Use the println function to print “Hello, World” to the console. 6. Run the program using the Run button (gutter icon). 7. Check the output in the Run tool window. 8. Select “Show Kotlin Bytecode” from the Tools > Kotlin menu. 9. Click “Decompile” in the Kotlin Bytecode window. 10. Check the output, and compare this generated Java file with the original Kotlin code.
Page 12
4 Exercise: Basic values operations What will be the result of the following expressions? fun main() { println(1 + 2 * 3) // ? println(10 % 3) // ? println(-1 % 3) // ? println(8.8 / 4) // ? println(10 / 3) // ? println(11.toFloat()) // ? println(10.10.toInt()) // ? var a = 10 a += 5 println(a) // ? a -= 3 println(a) // ? a++ println(a) // ? println(a++) // ? println(a) // ? println(--a) // ? println(a) // ? println(true && false) // ? println(true || false) // ? println(!!!!true) // ? println('A'.code) // 65 println('A' + 1) // ? println('C'.code) // ? println("A + B") // ? println("A" + "B") // ? println("A" + 1) // ? println("A" + 1 + 2) // ? }
Page 13
5 Exercise: Using when What will be the result of the following expressions? private val magicNumbers = listOf(7, 13) fun name(a: Any?): String = when (a) { null -> "Nothing" 1, 2, 3 -> "Small number" in magicNumbers -> "Magic number" in 4..100 -> "Big number" is String -> "String: $a" is Int, is Long -> "Int or Long: $a" else -> "No idea, really" } fun main() { println(name(1)) // ? println(name("A")) // ? println(name(null)) // ? println(name(5)) // ? println(name(100)) // ? println(name('A')) // ? println(name("1")) // ? println(name(-1)) // ? println(name(101)) // ? println(name(1L)) // ? println(name(7)) // ? println(name(3)) // ? println(name(3.0)) // ? println(name(100L)) // ? }
Page 14
6 Exercise: Pretty time display Implement the secondsToPrettyTime function that takes an integer number of seconds and returns a string representation of the time in the following format: “X h Y min Z sec”, where X, Y, and Z are the number of hours, minutes, and seconds respectively. If a value is zero, return “Now”. If the input is negative, return “Invalid input”. fun secondsToPrettyTime(seconds: Int): String { return "" } Example usage: println(secondsToPrettyTime(-1)) // Invalid input println(secondsToPrettyTime(0)) // Now println(secondsToPrettyTime(45)) // 45 sec println(secondsToPrettyTime(60)) // 1 min println(secondsToPrettyTime(150)) // 2 min 30 sec println(secondsToPrettyTime(1410)) // 23 min 30 sec println(secondsToPrettyTime(60 * 60)) // 1 h println(secondsToPrettyTime(3665)) // 1 h 1 min 5 sec Starting code, example usage and unit tests can be found in the MarcinMoskala/kotlin- exercises project on GitHub in the file essentials/conditions/PrettyTime.kt. You can clone this project and solve this exercise locally. Hint: You can use trim function on a string to remove leading and trailing whitespace characters.
Page 15
7 Exercise: Person details display Your task is to implement formatPersonDisplay function: It should have String result type and the following parameters: • name of type String? and default value null. • surname of type String? and default value null. • age of type Int? and default value null. Beware! Parameter types should include ?, so those should be String? and Int? instead of String and Int. This is because we want to allow passing null as a parameter value. This will be explained in the chapter Nullability. Function should return a string in the following format: "{name} {surname} ({age})". If any of the parameters is null, it should be omitted from the result. If all parameters are null, it should return an empty string. Here are some examples of how the function should work: println(formatPersonDisplay("John", "Smith", 42)) // John Smith (42) println(formatPersonDisplay("Alex", "Simonson")) // Alex Simonson println(formatPersonDisplay("Peter", age = 25)) // Peter (25) println(formatPersonDisplay(surname="Johnson", age=18)) // Johnson (18) Example usage and unit tests can be found in the MarcinMoskala/kotlin-exercises project on GitHub in the file essentials/functions/PersonDisplay.kt. You can clone this project and solve this exercise locally. In this project, example usage and unit tests are commented not to prevent other files from compilation. To uncomment them, select commented lines and use command + / on Mac (Ctrl + / on Windows) Hint: You can use trim function on a string to remove leading and trailing whitespace characters.
Page 16
8 Exercise: Range Operations Implement the following functions using range operations: • calculateSumOfSquares function that takes an integer n as an argument and returns the sum of the squares of all positive integers from 0 to n. • calculateSumOfEven function that takes an integer n as an argument and returns the sum of all even numbers from 0 to n. • countDownByStep function that takes three integers: start, end, and step, and returns a string representation of the numbers from start down to end, with each step being step units apart. fun calculateSumOfSquares(n: Int): Int = TODO() fun calculateSumOfEven(n: Int): Int = TODO() fun countDownByStep( start: Int, end: Int, step: Int ): String = TODO() Example usage: // Examples for calculateSumOfSquares println(calculateSumOfSquares(0)) // 0 println(calculateSumOfSquares(1)) // 1 println(calculateSumOfSquares(2)) // 5 (1 + 4) println(calculateSumOfSquares(3)) // 14 (1 + 4 + 9) println(calculateSumOfSquares(4)) // 30 (1 + 4 + 9 + 16) // Example for calculateSumOfEven println(calculateSumOfEven(0)) // 0 println(calculateSumOfEven(1)) // 0 println(calculateSumOfEven(2)) // 2 println(calculateSumOfEven(3)) // 2 println(calculateSumOfEven(5)) // 6 (2 + 4) println(calculateSumOfEven(10)) // 30 (2 + 4 + 6 + 8 + 10) println(calculateSumOfEven(12)) // 42 (2 + 4 + 6 + 8 + 10 + 12) println(calculateSumOfEven(20))
Page 17
9 // 110 (2 + 4 + 6 + 8 + 10 + 12 + 14 + 16 + 18 + 20) // Example for countDownByStep println(countDownByStep(1, 1, 1)) // 1 println(countDownByStep(5, 1, 2)) // 5, 3, 1 println(countDownByStep(10, 1, 3)) // 10, 7, 4, 1 println(countDownByStep(15, 5, 5)) // 15, 10, 5 println(countDownByStep(20, 2, 3)) // 20, 17, 14, 11, 8, 5, 2 println(countDownByStep(10, 4, 3)) // 10, 7, 4 println(countDownByStep(-1, -1, 1)) // -1 println(countDownByStep(-5, -9, 2)) // -5, -7, -9 Starting code, example usage and unit tests can be found in the MarcinMoskala/kotlin- exercises project on GitHub in the file essentials/loops/Loops.kt. You can clone this project and solve this exercise locally.
Page 18
10 Exercise: User Information Processor Implement the processUserInformation function according to the following rules: • If the input user is null, return "Missing user information". • If name from user is null, throw an IllegalArgumentException. • If age from user is null, treat it as 0. • If email from user is null or contains a blank email address, return "Missing email". • Otherwise, return information about user in the following format: “User {name} is {age} years old, email: {email}”. Starting code: fun processUserInformation(user: User?): String { return "" } data class EmailAddress(val email: String?) data class User( val name: String?, val age: Int?, val email: EmailAddress? ) Example usage: println(processUserInformation(null)) // Missing user information val user1 = User( "John", 30, EmailAddress("john@example.com") ) println(processUserInformation(user1)) // User John is 30 years old, email: john@example.com val user2 = User( "Alice", null, EmailAddress("alice@example.com")
Page 19
11 ) println(processUserInformation(user2)) // User Alice is 0 years old, email: alice@example.com val user3 = User( "Bob", 25, EmailAddress("") // or EmailAddress(null) or null ) println(processUserInformation(user3)) // Missing email val user6 = User( null, 40, EmailAddress("jake@example.com") ) println(processUserInformation(user6)) // IllegalArgumentException Starting code, example usage and unit tests can be found in the MarcinMoskala/kotlin- exercises project on GitHub in the file essentials/nullability/UserInformation.kt. You can clone this project and solve this exercise locally.
Page 20
12 Exercise: Implementing the Product class Define the Product class with properties: • name (String): The product’s name. • price (Double): The product’s price. • quantity (Int): The initial quantity of the product. Implement a custom setter for the quantity property that ensures that negative values are set to zero. Add a method named calculateTotalValue that returns the product’s total value. Implement a method named restock that increases the product’s quantity by a specified positive amount. If a negative value is specified, the method should do nothing. Instructions: 1. Define the Product class with primary constructor properties name, price, and parameter quantity. 2. Implement a property quantity with a custom setter. 3. Implement the calculateTotalValuemethod to calculate and return the total value. 4. Implement the restock method to increase the quantity. 5. Test your implementation by creating instances of the Product class and using its methods. Example usage: val laptop = Product("Laptop", 999.99, 5) println(laptop.name) // Laptop println(laptop.quantity) // 5 println(laptop.calculateTotalValue()) // 4999.95 laptop.restock(3) println(laptop.quantity) // 8 println(laptop.calculateTotalValue()) // 7999.92 laptop.quantity = -2 println(laptop.quantity) // 0 println(laptop.calculateTotalValue()) // 0.0
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List