diff --git a/README.md b/README.md index 760d3fd..e55641a 100644 --- a/README.md +++ b/README.md @@ -3,94 +3,99 @@ Learn Kotlin Programming, its basics and Fundamentals from scratch. ## Topics to be covered 0. Overview - - Course introduction, prequisites and software required + - [Course introduction, prerequisites and software required](docs/00-course-introduction.md) 1. Installation - - Install required softwares for Windows, MAC and Linux ( Ubuntu ) + - [Install required softwares for Windows, MAC and Linux ( Ubuntu )](docs/installation.md) 2. Getting Started with Kotlin Programming - - Run your first app in Kotlin + - [Run your first app in Kotlin](docs/basics/01-hello-world.md) 3. Exploring Data Types and Variables - - Data Types and Variables - - String, Literals and String Interpolation - - Comments + - [Data Types and Variables](docs/basics/02-variables-data-types.md) + - [String, Literals and String Interpolation](docs/basics/05-string-interpolation.md) + - [Comments](docs/basics/03-comments.md) 4. Constants, Variables and Data Types + - [Data Types Deep Dive](docs/basics/04-data-types.md) 5. Control Flow Statements - - IF ELSE - - IF Expressions - - WHEN Expressions + - [IF ELSE and IF Expressions](docs/control-flow/01-if-expressions.md) + - [WHEN Expressions](docs/control-flow/02-when-expressions.md) 6. Loop Control Statements - - What are Iterators? - - FOR Loop and how it works - - WHILE Loop - - DO WHILE Loop - - BREAK statements - - CONTINUE keyword - - Labelled FOR Loop + - [What are Iterators?](docs/control-flow/06-iterators.md) + - [FOR Loop and how it works](docs/control-flow/03-for-loops.md) + - [WHILE Loop](docs/control-flow/04-while-loops.md) + - [DO WHILE Loop](docs/control-flow/04-while-loops.md) + - [BREAK statements](docs/control-flow/05-break-continue.md) + - [CONTINUE keyword](docs/control-flow/05-break-continue.md) + - [Labelled FOR Loop](docs/control-flow/07-labelled-loops.md) 7. Functions and Interoperability - - Declaring functions - - Interoperability with Java code - - Function as Expressions - - Extension Functions - - Infix Functions - - Default Parameters - - Named Parameters - - Tailrec Functions + - [Declaring functions](docs/functions/01-functions-basics.md) + - [Interoperability with Java code](docs/advanced/01-kotlin-interoperability.md) + - [Function as Expressions](docs/functions/02-functions-as-expressions.md) + - [Extension Functions](docs/functions/04-extension-functions.md) + - [Infix Functions](docs/functions/05-infix-functions.md) + - [Default Parameters](docs/functions/06-default-parameters.md) + - [Named Parameters](docs/functions/03-named-parameters.md) + - [Tailrec Functions](docs/functions/07-tailrec-functions.md) 8. Object Oriented Programming in Kotlin - - Defining Class and creating Objects - - INIT block - - Primary and Secondary Constructors - - Properties ( Field variables ) - - Inheritance - - Method and Property Overriding - - Polymorphism - - Abstract Class, Property and Method - - Interface - - Data Class - - Object Declaration - - Enum class - - Sealed class - - Companion Object + - [Defining Class, creating Objects, and Constructors](docs/oop/01-classes-constructors.md) + - [INIT block](docs/oop/05-init-block.md) + - [Properties ( Field variables )](docs/oop/06-properties.md) + - [Inheritance](docs/oop/02-inheritance.md) + - [Method and Property Overriding](docs/oop/03-method-overriding.md) + - [Polymorphism](docs/oop/08-polymorphism.md) + - [Abstract Class, Property and Method](docs/oop/04-abstract-classes.md) + - [Interface](docs/oop/09-interface.md) + - [Data Class](docs/oop/10-data-class.md) + - [Object Declaration](docs/oop/11-object-declaration.md) + - [Enum class](docs/oop/07-enums-sealed-classes.md) + - [Sealed class](docs/oop/07-enums-sealed-classes.md) + - [Companion Object](docs/oop/12-companion-object.md) 9. Functional Programming in Koltin - - Lambdas - - Higher-Order Functions - - Closures - - 'it' keyword - - 'with' function - - 'apply' function + - [Lambdas](docs/functional-programming/01-lambdas.md) + - [Higher-Order Functions](docs/functional-programming/05-higher-order-functions.md) + - [Closures](docs/functional-programming/06-closures.md) + - ['it' keyword](docs/functional-programming/07-it-keyword.md) + - ['with' function](docs/functional-programming/02-scope-functions.md) + - ['apply' function](docs/functional-programming/02-scope-functions.md) + - [let, also, run](docs/functional-programming/03-let-also-run.md) 10. Collections in Kotlin - - Arrays - - List - - Map and HashMap - - Set and HashSet + - [Arrays](docs/collections/01-arrays.md) + - [List](docs/collections/02-lists.md) + - [Map and HashMap](docs/collections/03-maps.md) + - [Set and HashSet](docs/collections/04-sets.md) 11. Sorting and Filtering - - "filter" function - - "map" function - - Predicates: all, any, find, count. + - ["filter" function](docs/collections/05-filter-map-sorting.md) + - ["map" function](docs/collections/05-filter-map-sorting.md) + - [Predicates: all, any, find, count](docs/functional-programming/04-predicates.md) 12. Kotlin NULL Safety - - Safe call - - with Let - - Elvis - - Lateinit keyword - - Lazy delegation and 'lateinit' vs. 'lazy' + - [Safe call](docs/null-safety/01-null-safety.md) + - [with Let](docs/null-safety/01-null-safety.md) + - [Elvis](docs/null-safety/01-null-safety.md) + - [Lateinit keyword](docs/null-safety/02-lateinit-lazy.md) + - [Lazy delegation and 'lateinit' vs. 'lazy'](docs/null-safety/02-lateinit-lazy.md) 13. Scope Functions - - with - - apply - - let - - also - - run + - [with](docs/functional-programming/02-scope-functions.md) + - [apply](docs/functional-programming/02-scope-functions.md) + - [let](docs/functional-programming/03-let-also-run.md) + - [also](docs/functional-programming/03-let-also-run.md) + - [run](docs/functional-programming/03-let-also-run.md) 14. Coroutines - - What are Coroutines? How are they related to Threads? - - launch, async, runBlocking, withContext, withTimeoutOrNull, - - Suspending function - - Cancellation and Timeouts - - Cooperative suspending functions and isActive flag - - Exception Handling in Coroutines - - Sequential execution of suspending function in Coroutines - - Concurrency within Coroutine - - lazy 'async' - - CoroutineScope and CoroutineContext - - Dispacthers: Confined dispatcher, Default Dispatcher, and Unconfined Displatcher -15. Conclusion + - [What are Coroutines? How are they related to Threads?](docs/coroutines/01-introduction.md) + - [launch, async, runBlocking](docs/coroutines/02-launch-async.md) + - [withContext, withTimeoutOrNull](docs/coroutines/04-context-dispatchers.md) + - [Suspending function](docs/coroutines/01-introduction.md) + - [Cancellation and Timeouts](docs/coroutines/03-exception-handling.md) + - [Cooperative suspending functions and isActive flag](docs/coroutines/01-introduction.md) + - [Exception Handling in Coroutines](docs/coroutines/03-exception-handling.md) + - [Sequential execution of suspending function in Coroutines](docs/coroutines/02-launch-async.md) + - [Concurrency within Coroutine](docs/coroutines/02-launch-async.md) + - [lazy 'async'](docs/coroutines/02-launch-async.md) + - [CoroutineScope and CoroutineContext](docs/coroutines/04-context-dispatchers.md) + - [Dispatchers: Confined dispatcher, Default Dispatcher, and Unconfined Dispatcher](docs/coroutines/04-context-dispatchers.md) +15. [Conclusion](docs/conclusion.md) ## Authors -* **Sriyank Siddhartha** +* **Sriyank Siddhartha** - Original creator + +## Contributors + +* **GPL Gowtham chand** ([@gpl-gowthamchand](https://github.com/gpl-gowthamchand)) - Documentation, explanations, and content organization diff --git a/docs/00-course-introduction.md b/docs/00-course-introduction.md new file mode 100644 index 0000000..d0c88cc --- /dev/null +++ b/docs/00-course-introduction.md @@ -0,0 +1,245 @@ +# ๐Ÿš€ Kotlin Programming Tutorial - Course Introduction + +Welcome to the comprehensive Kotlin Programming Tutorial! This course is designed to take you from a complete beginner to a confident Kotlin developer. + +## ๐Ÿ“‹ Course Overview + +This tutorial covers all the essential concepts of Kotlin programming, from basic syntax to advanced features like coroutines and functional programming. Whether you're new to programming or an experienced developer looking to learn Kotlin, this course has something for you. + +## ๐ŸŽฏ Learning Objectives + +By the end of this course, you will be able to: +- โœ… Write, compile, and run Kotlin programs +- โœ… Understand and use Kotlin's basic syntax and data types +- โœ… Implement control flow structures (if, when, loops) +- โœ… Create and use functions with various parameter types +- โœ… Work with object-oriented programming concepts +- โœ… Utilize functional programming features +- โœ… Handle collections and null safety effectively +- โœ… Use coroutines for asynchronous programming +- โœ… Apply best practices and design patterns + +## ๐Ÿ“š Course Structure + +The course is organized into logical sections: + +1. **Basics** - Hello World, variables, data types, comments +2. **Control Flow** - Conditional statements and loops +3. **Functions** - Function declaration, parameters, extensions +4. **Object-Oriented Programming** - Classes, inheritance, interfaces +5. **Functional Programming** - Lambdas, higher-order functions +6. **Collections** - Arrays, lists, maps, sets +7. **Null Safety** - Safe calls, Elvis operator, lateinit +8. **Scope Functions** - with, apply, let, also, run +9. **Coroutines** - Asynchronous programming +10. **Advanced Topics** - Generics, reflection, testing + +## ๐Ÿ”ง Prerequisites + +### **Programming Experience** +- **Beginner-friendly**: No prior programming experience required +- **Basic concepts**: Understanding of variables, functions, and logic helps +- **Math skills**: Basic arithmetic and logical thinking + +### **Computer Skills** +- **File management**: Ability to create, save, and organize files +- **Text editing**: Comfortable using a text editor or IDE +- **Command line**: Basic familiarity with terminal/command prompt (helpful but not required) + +### **Learning Mindset** +- **Patience**: Programming takes time to master +- **Practice**: Willingness to experiment and practice regularly +- **Problem-solving**: Enjoyment of logical thinking and problem-solving + +## ๐Ÿ’ป Software Requirements + +### **1. Java Development Kit (JDK)** + +**Why JDK?** +Kotlin runs on the Java Virtual Machine (JVM), so you need a JDK to compile and run Kotlin programs. + +**Recommended Version:** +- **JDK 8** (minimum) +- **JDK 11** (recommended) +- **JDK 17** (latest LTS) + +**Installation:** +- **Windows**: Download from Oracle or use OpenJDK +- **macOS**: Use Homebrew or download from Oracle +- **Linux**: Use package manager or download from Oracle + +### **2. Kotlin Compiler** + +**Options:** +- **Kotlin command-line compiler** (kotlinc) +- **Gradle** (build tool with Kotlin support) +- **Maven** (build tool with Kotlin support) + +**Installation:** +- **SDKMAN!** (Linux/macOS): `sdk install kotlin` +- **Homebrew** (macOS): `brew install kotlin` +- **Manual**: Download from [kotlinlang.org](https://kotlinlang.org) + +### **3. Integrated Development Environment (IDE)** + +**Recommended IDEs:** + +#### **IntelliJ IDEA (Recommended)** +- **Community Edition**: Free, full-featured +- **Ultimate Edition**: Paid, additional features +- **Kotlin Support**: Excellent, first-class support +- **Features**: Code completion, refactoring, debugging + +#### **Android Studio** +- **Free**: Completely free +- **Kotlin Support**: Excellent +- **Android Development**: Perfect if you plan to develop Android apps +- **Features**: Full IDE with Android-specific tools + +#### **Visual Studio Code** +- **Free**: Completely free +- **Kotlin Support**: Good with extensions +- **Extensions**: Kotlin Language, Kotlin Extension Pack +- **Features**: Lightweight, fast, extensible + +#### **Eclipse** +- **Free**: Completely free +- **Kotlin Support**: Good with plugins +- **Plugin**: Kotlin Plugin for Eclipse +- **Features**: Familiar to Java developers + +### **4. Text Editor (Alternative)** + +**For minimal setup:** +- **Notepad++** (Windows) +- **Sublime Text** (Cross-platform) +- **Atom** (Cross-platform) +- **Vim/Emacs** (Advanced users) + +## ๐Ÿš€ Getting Started + +### **Step 1: Install Java (JDK)** +1. Download JDK from [Oracle](https://www.oracle.com/java/technologies/) or [OpenJDK](https://openjdk.java.net/) +2. Install following the installation wizard +3. Verify installation: `java -version` and `javac -version` + +### **Step 2: Install Kotlin** +1. Choose your preferred method (SDKMAN!, Homebrew, or manual) +2. Verify installation: `kotlinc -version` + +### **Step 3: Choose Your IDE** +1. Download and install your preferred IDE +2. Install Kotlin plugin if required +3. Create your first Kotlin project + +### **Step 4: Verify Setup** +1. Create a simple "Hello World" program +2. Compile and run it +3. Ensure everything works correctly + +## ๐Ÿ“– How to Use This Course + +### **Learning Path** +1. **Start with Basics**: Begin with Hello World and fundamental concepts +2. **Follow the Order**: Each lesson builds on previous knowledge +3. **Practice Regularly**: Complete exercises and experiment with code +4. **Review and Reinforce**: Revisit concepts you find challenging + +### **Code Examples** +- **Source Files**: Each lesson references actual Kotlin source files +- **Live Coding**: Try the examples as you read +- **Modification**: Experiment with changing values and logic +- **Extension**: Build upon examples to create your own programs + +### **Exercises and Projects** +- **Practice Exercises**: Complete the exercises at the end of each lesson +- **Mini Projects**: Build small applications to reinforce concepts +- **Real-world Examples**: Apply what you learn to practical scenarios + +## ๐ŸŽฏ Success Tips + +### **1. Code Every Day** +- Practice coding regularly, even if just for 30 minutes +- Consistency is more important than long sessions +- Build a habit of daily practice + +### **2. Understand, Don't Memorize** +- Focus on understanding concepts rather than memorizing syntax +- Learn why things work, not just how +- Ask questions and seek clarification + +### **3. Build Projects** +- Start with simple projects and gradually increase complexity +- Apply what you learn to real problems +- Share your projects and get feedback + +### **4. Use Resources** +- Official Kotlin documentation: [kotlinlang.org](https://kotlinlang.org) +- Kotlin community forums and discussions +- Online coding platforms (LeetCode, HackerRank) +- Open source projects for inspiration + +### **5. Join the Community** +- Participate in Kotlin discussions +- Attend meetups and conferences +- Contribute to open source projects +- Help other learners + +## ๐Ÿ” Troubleshooting + +### **Common Issues** + +#### **"Java not found" error** +- Ensure JDK is properly installed +- Check PATH environment variable +- Verify JAVA_HOME is set correctly + +#### **"Kotlin not found" error** +- Ensure Kotlin is properly installed +- Check PATH environment variable +- Verify installation with `kotlinc -version` + +#### **IDE not recognizing Kotlin** +- Install Kotlin plugin/extension +- Restart IDE after installation +- Check project configuration + +#### **Compilation errors** +- Check syntax carefully +- Verify all required imports +- Ensure proper file structure + +### **Getting Help** +- **Documentation**: Check official Kotlin docs +- **Community**: Ask questions on Stack Overflow or Reddit +- **Forums**: Use Kotlin community forums +- **GitHub**: Check issues and discussions on Kotlin repositories + +## ๐Ÿ“š Additional Resources + +### **Official Documentation** +- [Kotlin Language Documentation](https://kotlinlang.org/docs/home.html) +- [Kotlin API Reference](https://kotlinlang.org/api/latest/jvm/stdlib/) +- [Kotlin Playground](https://play.kotlinlang.org/) + +### **Books and Courses** +- "Kotlin in Action" by Dmitry Jemerov and Svetlana Isakova +- "Kotlin Programming: The Big Nerd Ranch Guide" +- Online courses on platforms like Udemy, Coursera, and edX + +### **Practice Platforms** +- [LeetCode](https://leetcode.com/) - Algorithm problems +- [HackerRank](https://www.hackerrank.com/) - Coding challenges +- [Exercism](https://exercism.org/) - Language track exercises + +## ๐ŸŽ‰ Ready to Start? + +You're all set to begin your Kotlin programming journey! The next lesson will guide you through creating your first Kotlin program - the classic "Hello World" application. + +**Remember**: Learning to program is a journey, not a destination. Take your time, practice regularly, and don't be afraid to make mistakes. Every error is an opportunity to learn! + +--- + +**Next Lesson**: [Hello World](basics/01-hello-world.md) - Create your first Kotlin program + +**Happy coding! ๐Ÿš€** diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..7112be6 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,101 @@ +# Kotlin Programming Tutorial for Beginners +Learn Kotlin Programming, its basics and Fundamentals from scratch. + +## Topics to be covered +0. Overview + - [Course introduction, prerequisites and software required](00-course-introduction.md) +1. Installation + - [Install required softwares for Windows, MAC and Linux ( Ubuntu )](installation.md) +2. Getting Started with Kotlin Programming + - [Run your first app in Kotlin](basics/01-hello-world.md) +3. Exploring Data Types and Variables + - [Data Types and Variables](basics/02-variables-data-types.md) + - [String, Literals and String Interpolation](basics/05-string-interpolation.md) + - [Comments](basics/03-comments.md) +4. Constants, Variables and Data Types + - [Data Types Deep Dive](basics/04-data-types.md) +5. Control Flow Statements + - [IF ELSE and IF Expressions](control-flow/01-if-expressions.md) + - [WHEN Expressions](control-flow/02-when-expressions.md) +6. Loop Control Statements + - [What are Iterators?](control-flow/06-iterators.md) + - [FOR Loop and how it works](control-flow/03-for-loops.md) + - [WHILE Loop](control-flow/04-while-loops.md) + - [DO WHILE Loop](control-flow/04-while-loops.md) + - [BREAK statements](control-flow/05-break-continue.md) + - [CONTINUE keyword](control-flow/05-break-continue.md) + - [Labelled FOR Loop](control-flow/07-labelled-loops.md) +7. Functions and Interoperability + - [Declaring functions](functions/01-functions-basics.md) + - [Interoperability with Java code](advanced/01-kotlin-interoperability.md) + - [Function as Expressions](functions/02-functions-as-expressions.md) + - [Extension Functions](functions/04-extension-functions.md) + - [Infix Functions](functions/05-infix-functions.md) + - [Default Parameters](functions/06-default-parameters.md) + - [Named Parameters](functions/03-named-parameters.md) + - [Tailrec Functions](functions/07-tailrec-functions.md) +8. Object Oriented Programming in Kotlin + - [Defining Class, creating Objects, and Constructors](oop/01-classes-constructors.md) + - [INIT block](oop/05-init-block.md) + - [Properties ( Field variables )](oop/06-properties.md) + - [Inheritance](oop/02-inheritance.md) + - [Method and Property Overriding](oop/03-method-overriding.md) + - [Polymorphism](oop/08-polymorphism.md) + - [Abstract Class, Property and Method](oop/04-abstract-classes.md) + - [Interface](oop/09-interface.md) + - [Data Class](oop/10-data-class.md) + - [Object Declaration](oop/11-object-declaration.md) + - [Enum class](oop/07-enums-sealed-classes.md) + - [Sealed class](oop/07-enums-sealed-classes.md) + - [Companion Object](oop/12-companion-object.md) +9. Functional Programming in Koltin + - [Lambdas](functional-programming/01-lambdas.md) + - [Higher-Order Functions](functional-programming/05-higher-order-functions.md) + - [Closures](functional-programming/06-closures.md) + - ['it' keyword](functional-programming/07-it-keyword.md) + - ['with' function](functional-programming/02-scope-functions.md) + - ['apply' function](functional-programming/02-scope-functions.md) + - [let, also, run](functional-programming/03-let-also-run.md) +10. Collections in Kotlin + - [Arrays](collections/01-arrays.md) + - [List](collections/02-lists.md) + - [Map and HashMap](collections/03-maps.md) + - [Set and HashSet](collections/04-sets.md) +11. Sorting and Filtering + - ["filter" function](collections/05-filter-map-sorting.md) + - ["map" function](collections/05-filter-map-sorting.md) + - [Predicates: all, any, find, count](functional-programming/04-predicates.md) +12. Kotlin NULL Safety + - [Safe call](null-safety/01-null-safety.md) + - [with Let](null-safety/01-null-safety.md) + - [Elvis](null-safety/01-null-safety.md) + - [Lateinit keyword](null-safety/02-lateinit-lazy.md) + - [Lazy delegation and 'lateinit' vs. 'lazy'](null-safety/02-lateinit-lazy.md) +13. Scope Functions + - [with](functional-programming/02-scope-functions.md) + - [apply](functional-programming/02-scope-functions.md) + - [let](functional-programming/03-let-also-run.md) + - [also](functional-programming/03-let-also-run.md) + - [run](functional-programming/03-let-also-run.md) +14. Coroutines + - [What are Coroutines? How are they related to Threads?](coroutines/01-introduction.md) + - [launch, async, runBlocking](coroutines/02-launch-async.md) + - [withContext, withTimeoutOrNull](coroutines/04-context-dispatchers.md) + - [Suspending function](coroutines/01-introduction.md) + - [Cancellation and Timeouts](coroutines/03-exception-handling.md) + - [Cooperative suspending functions and isActive flag](coroutines/01-introduction.md) + - [Exception Handling in Coroutines](coroutines/03-exception-handling.md) + - [Sequential execution of suspending function in Coroutines](coroutines/02-launch-async.md) + - [Concurrency within Coroutine](coroutines/02-launch-async.md) + - [lazy 'async'](coroutines/02-launch-async.md) + - [CoroutineScope and CoroutineContext](coroutines/04-context-dispatchers.md) + - [Dispatchers: Confined dispatcher, Default Dispatcher, and Unconfined Dispatcher](coroutines/04-context-dispatchers.md) +15. [Conclusion](conclusion.md) + +## Authors + +* **Sriyank Siddhartha** - Original creator + +## Contributors + +* **GPL Gowtham chand** ([@gpl-gowthamchand](https://github.com/gpl-gowthamchand)) - Documentation, explanations, and content organization diff --git a/docs/advanced/01-kotlin-interoperability.md b/docs/advanced/01-kotlin-interoperability.md new file mode 100644 index 0000000..f357bd8 --- /dev/null +++ b/docs/advanced/01-kotlin-interoperability.md @@ -0,0 +1,618 @@ +# ๐Ÿ”„ Kotlin-Java Interoperability + +This lesson covers Kotlin-Java interoperability, which allows you to use Java code from Kotlin and vice versa. This is essential for working with existing Java libraries and gradually migrating Java projects to Kotlin. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Call Java code from Kotlin seamlessly +- โœ… Use Kotlin code from Java +- โœ… Handle null safety differences between languages +- โœ… Work with Java collections and Kotlin collections +- โœ… Apply best practices for interoperability + +## ๐Ÿ” What You'll Learn + +- **Java from Kotlin** - Calling Java methods and classes +- **Kotlin from Java** - Using Kotlin classes in Java +- **Null Safety** - Handling nullable types across languages +- **Collections** - Working with Java and Kotlin collections +- **Best Practices** - Guidelines for smooth interoperability + +## ๐Ÿ“ Prerequisites + +- Understanding of [Kotlin Basics](../basics/README.md) +- Knowledge of [Null Safety](../null-safety/01-null-safety.md) +- Familiarity with [Collections](../collections/README.md) +- Basic Java knowledge + +## ๐Ÿ’ป The Code + +Let's examine the interoperability examples: + +**๐Ÿ“ File:** [MyJavaFile.java](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/MyJavaFile.java) +**๐Ÿ“ File:** [myKotlinInteroperability.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/myKotlinInteroperability.kt) + +## ๐Ÿ” Code Breakdown + +### **1. Calling Java from Kotlin** + +#### **Basic Java Class Usage** +```kotlin +// Java class can be used directly in Kotlin +fun main() { + val javaClass = MyJavaClass() + + // Call Java methods + javaClass.setName("John Doe") + javaClass.setAge(30) + + // Access Java properties (getters/setters) + println("Name: ${javaClass.name}") + println("Age: ${javaClass.age}") + + // Call Java methods with different signatures + javaClass.printInfo() + javaClass.printInfo("Custom prefix") +} +``` + +#### **Java Collections in Kotlin** +```kotlin +fun main() { + // Java ArrayList + val javaList = java.util.ArrayList() + javaList.add("Item 1") + javaList.add("Item 2") + + // Use Kotlin collection functions + val filtered = javaList.filter { it.contains("1") } + val mapped = javaList.map { "Processed: $it" } + + println("Original: $javaList") + println("Filtered: $filtered") + println("Mapped: $mapped") + + // Convert to Kotlin collections + val kotlinList = javaList.toList() + val kotlinMutableList = javaList.toMutableList() +} +``` + +#### **Java Static Methods** +```kotlin +fun main() { + // Call Java static methods + val random = MyJavaClass.generateRandomNumber() + val formatted = MyJavaClass.formatString("Hello", "World") + + println("Random number: $random") + println("Formatted string: $formatted") + + // Access Java constants + println("Max value: ${MyJavaClass.MAX_VALUE}") + println("Default name: ${MyJavaClass.DEFAULT_NAME}") +} +``` + +### **2. Using Kotlin from Java** + +#### **Kotlin Class in Java** +```java +public class JavaClient { + public static void main(String[] args) { + // Create Kotlin object + MyKotlinClass kotlinObject = new MyKotlinClass("Kotlin", 42); + + // Call Kotlin methods + String info = kotlinObject.getInfo(); + System.out.println("Info: " + info); + + // Access Kotlin properties + String name = kotlinObject.getName(); + int value = kotlinObject.getValue(); + System.out.println("Name: " + name + ", Value: " + value); + + // Call Kotlin functions with default parameters + String result = kotlinObject.processData("input", true); + System.out.println("Result: " + result); + } +} +``` + +#### **Kotlin Functions with Default Parameters** +```kotlin +class MyKotlinClass(val name: String, val value: Int) { + fun getInfo(): String = "Name: $name, Value: $value" + + fun processData(input: String, verbose: Boolean = false): String { + return if (verbose) { + "Processing '$input' with verbose output" + } else { + "Processed: $input" + } + } + + fun getValue(): Int = value +} +``` + +### **3. Null Safety Interoperability** + +#### **Java Nullable Types in Kotlin** +```kotlin +fun main() { + val javaClass = MyJavaClass() + + // Java methods can return null + val nullableString = javaClass.getNullableString() + + // Handle null safely + if (nullableString != null) { + println("String length: ${nullableString.length}") + } else { + println("String is null") + } + + // Use safe call operator + println("String length: ${nullableString?.length}") + + // Use Elvis operator for default value + val safeString = nullableString ?: "Default string" + println("Safe string: $safeString") +} +``` + +#### **Kotlin Non-Null Types in Java** +```kotlin +class KotlinService { + fun getNonNullString(): String = "Always returns a string" + + fun getNullableString(): String? = null + + fun processString(input: String) { + println("Processing: $input") + } +} +``` + +```java +public class JavaClient { + public static void main(String[] args) { + KotlinService service = new KotlinService(); + + // Kotlin non-null String becomes Java String + String nonNull = service.getNonNullString(); + service.processString(nonNull); // Safe to call + + // Kotlin nullable String becomes Java String (with @Nullable annotation) + String nullable = service.getNullableString(); + if (nullable != null) { + service.processString(nullable); + } + } +} +``` + +### **4. Collection Interoperability** + +#### **Java Collections in Kotlin** +```kotlin +fun main() { + // Java HashMap + val javaMap = java.util.HashMap() + javaMap.put("one", 1) + javaMap.put("two", 2) + javaMap.put("three", 3) + + // Use Kotlin collection functions + val filteredMap = javaMap.filter { (key, value) -> value> 1 } + val keys = javaMap.keys.toList() + val values = javaMap.values.toList() + + println("Original map: $javaMap") + println("Filtered map: $filteredMap") + println("Keys: $keys") + println("Values: $values") + + // Convert to Kotlin collections + val kotlinMap = javaMap.toMap() + val kotlinMutableMap = javaMap.toMutableMap() +} +``` + +#### **Kotlin Collections in Java** +```kotlin +class KotlinCollectionProvider { + fun getList(): List = listOf("a", "b", "c") + + fun getMutableList(): MutableList = mutableListOf("x", "y", "z") + + fun getMap(): Map = mapOf("one" to 1, "two" to 2) + + fun getSet(): Set = setOf("alpha", "beta", "gamma") +} +``` + +```java +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class JavaCollectionClient { + public static void main(String[] args) { + KotlinCollectionProvider provider = new KotlinCollectionProvider(); + + // Kotlin List becomes Java List + List list = provider.getList(); + System.out.println("List: " + list); + + // Kotlin MutableList becomes Java List + List mutableList = provider.getMutableList(); + mutableList.add("new"); + System.out.println("Mutable list: " + mutableList); + + // Kotlin Map becomes Java Map + Map map = provider.getMap(); + System.out.println("Map: " + map); + + // Kotlin Set becomes Java Set + Set set = provider.getSet(); + System.out.println("Set: " + set); + } +} +``` + +### **5. Advanced Interoperability Patterns** + +#### **Java Builder Pattern in Kotlin** +```kotlin +fun main() { + // Use Java builder pattern + val person = PersonBuilder() + .setName("Jane Doe") + .setAge(25) + .setEmail("jane@example.com") + .build() + + println("Person: $person") + + // Use Java fluent API + val config = ConfigurationBuilder() + .setHost("localhost") + .setPort(8080) + .setTimeout(5000) + .build() + + println("Config: $config") +} +``` + +#### **Kotlin Extension Functions on Java Classes** +```kotlin +// Extend Java classes with Kotlin functions +fun java.util.ArrayList.addIfNotExists(item: String): Boolean { + return if (this.contains(item)) { + false + } else { + this.add(item) + true + } +} + +fun java.util.HashMap.getString(key: String): String? { + return this[key] as? String +} + +fun main() { + val javaList = java.util.ArrayList() + javaList.addIfNotExists("first") + javaList.addIfNotExists("second") + javaList.addIfNotExists("first") // Won't add duplicate + + println("List: $javaList") + + val javaMap = java.util.HashMap() + javaMap["name"] = "John" + javaMap["age"] = 30 + + val name = javaMap.getString("name") + println("Name: $name") +} +``` + +#### **Java SAM (Single Abstract Method) Interfaces** +```kotlin +fun main() { + // Java Runnable interface + val runnable = java.lang.Runnable { println("Running from Kotlin") } + + // Java Thread with Kotlin lambda + val thread = java.lang.Thread { println("Thread running") } + thread.start() + + // Java Comparator + val names = listOf("Charlie", "Alice", "Bob") + val sortedNames = names.sortedWith(java.util.Comparator { a, b -> a.compareTo(b) }) + + println("Sorted names: $sortedNames") +} +``` + +## ๐ŸŽฏ Key Concepts Explained + +### **1. Type Mapping** + +| Kotlin Type | Java Type | Notes | +|-------------|-----------|-------| +| `String` | `String` | Non-null String | +| `String?` | `String` | Nullable String (with annotations) | +| `Int` | `int` | Primitive int | +| `Int?` | `Integer` | Nullable Integer | +| `List` | `List` | Read-only list | +| `MutableList` | `List` | Mutable list | + +### **2. Null Safety Differences** +- **Kotlin**: Compile-time null safety +- **Java**: Runtime null safety +- **Interop**: Kotlin nullable types become Java types with `@Nullable` annotations +- **Best Practice**: Always check for null when calling Java methods + +### **3. Collection Differences** +- **Kotlin**: Read-only vs mutable collections +- **Java**: All collections are mutable +- **Interop**: Kotlin read-only collections become Java collections (mutable) + +## ๐Ÿงช Running the Examples + +### **Step 1: Open the Files** +1. Navigate to `src/MyJavaFile.java` +2. Navigate to `src/myKotlinInteroperability.kt` +3. Open them in IntelliJ IDEA + +### **Step 2: Run the Programs** +1. Right-click on the Kotlin file +2. Select "Run 'myKotlinInteroperabilityKt'" +3. Observe the output + +## ๐ŸŽฎ Hands-On Exercises + +### **Exercise 1: Java Library Integration** +Create a Kotlin program that uses Java libraries like Apache Commons. + +**Solution:** +```kotlin +import org.apache.commons.lang3.StringUtils +import java.util.Random + +fun main() { + // Use Java Random class + val random = Random() + val randomNumber = random.nextInt(100) + println("Random number: $randomNumber") + + // Use Apache Commons StringUtils + val text = " hello world " + val trimmed = StringUtils.trim(text) + val capitalized = StringUtils.capitalize(trimmed) + val reversed = StringUtils.reverse(capitalized) + + println("Original: '$text'") + println("Trimmed: '$trimmed'") + println("Capitalized: '$capitalized'") + println("Reversed: '$reversed'") + + // Use Java Collections + val javaList = java.util.ArrayList() + javaList.add("item1") + javaList.add("item2") + + // Convert to Kotlin and use Kotlin functions + val kotlinList = javaList.toList() + val processed = kotlinList.map { "Processed: $it" } + println("Processed: $processed") +} +``` + +### **Exercise 2: Kotlin Service in Java** +Create a Kotlin service that can be easily used from Java. + +**Solution:** +```kotlin +// Kotlin service designed for Java interop +class UserService { + private val users = mutableMapOf() + + fun createUser(name: String, email: String): User { + val user = User(name, email) + users[email] = user + return user + } + + fun getUser(email: String): User? = users[email] + + fun getAllUsers(): List = users.values.toList() + + fun updateUser(email: String, newName: String): Boolean { + val user = users[email] ?: return false + users[email] = user.copy(name = newName) + return true + } + + fun deleteUser(email: String): Boolean { + return users.remove(email) != null + } +} + +data class User(val name: String, val email: String) +``` + +```java +// Java client using Kotlin service +public class JavaUserClient { + public static void main(String[] args) { + UserService service = new UserService(); + + // Create users + User user1 = service.createUser("John Doe", "john@example.com"); + User user2 = service.createUser("Jane Smith", "jane@example.com"); + + System.out.println("Created users: " + user1 + ", " + user2); + + // Get all users + List allUsers = service.getAllUsers(); + System.out.println("All users: " + allUsers); + + // Update user + boolean updated = service.updateUser("john@example.com", "John Updated"); + System.out.println("Update successful: " + updated); + + // Get updated user + User updatedUser = service.getUser("john@example.com"); + System.out.println("Updated user: " + updatedUser); + } +} +``` + +### **Exercise 3: Collection Interoperability** +Create a program that demonstrates collection interoperability. + +**Solution:** +```kotlin +fun main() { + // Java collections + val javaArrayList = java.util.ArrayList() + val javaHashMap = java.util.HashMap() + + // Populate Java collections + for (i in 1..5) { + javaArrayList.add(i * i) + javaHashMap["key$i"] = i + } + + println("Java ArrayList: $javaArrayList") + println("Java HashMap: $javaHashMap") + + // Convert to Kotlin collections + val kotlinList = javaArrayList.toList() + val kotlinMap = javaHashMap.toMap() + + // Use Kotlin collection functions + val filteredList = kotlinList.filter { it> 10 } + val transformedMap = kotlinMap.mapValues { (key, value) -> value * 2 } + + println("Filtered list (>10): $filteredList") + println("Transformed map (values * 2): $transformedMap") + + // Convert back to Java collections + val backToJavaList = kotlinList.toMutableList() + val backToJavaMap = kotlinMap.toMutableMap() + + // Use Java collection methods + backToJavaList.add(36) + backToJavaMap.put("newKey", 100) + + println("Modified Java list: $backToJavaList") + println("Modified Java map: $backToJavaMap") +} +``` + +### **Exercise 4: Null Safety Bridge** +Create a system that safely bridges null safety between Kotlin and Java. + +**Solution:** +```kotlin +// Kotlin class with null safety +class SafeDataProcessor { + fun processData(data: String): String { + return "Processed: $data" + } + + fun processNullableData(data: String?): String? { + return data?.let { "Processed: $it" } + } + + fun getDefaultValue(): String = "Default value" + + fun getNullableValue(): String? = null +} + +// Java-friendly wrapper +class JavaFriendlyWrapper { + private val processor = SafeDataProcessor() + + fun processData(data: String): String { + return processor.processData(data) + } + + fun processNullableData(data: String?): String { + return processor.processNullableData(data) ?: "No data provided" + } + + fun getDefaultValue(): String = processor.getDefaultValue() + + fun getNullableValue(): String? = processor.getNullableValue() +} +``` + +```java +public class JavaNullSafetyClient { + public static void main(String[] args) { + JavaFriendlyWrapper wrapper = new JavaFriendlyWrapper(); + + // Safe non-null operations + String result1 = wrapper.processData("Hello"); + System.out.println("Result 1: " + result1); + + // Handle nullable data safely + String result2 = wrapper.processNullableData("World"); + System.out.println("Result 2: " + result2); + + String result3 = wrapper.processNullableData(null); + System.out.println("Result 3: " + result3); + + // Get values + String defaultValue = wrapper.getDefaultValue(); + System.out.println("Default: " + defaultValue); + + String nullableValue = wrapper.getNullableValue(); + if (nullableValue != null) { + System.out.println("Nullable: " + nullableValue); + } else { + System.out.println("Nullable value is null"); + } + } +} +``` + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Ignoring null safety**: Always check for null when calling Java methods โœ… +2. **Collection mutability**: Remember that Java collections are always mutable โœ… +3. **Type mismatches**: Be aware of primitive vs wrapper type differences โœ… +4. **Forgetting annotations**: Use proper annotations for Java interop โœ… + +## ๐ŸŽฏ What's Next? + +Now that you understand Kotlin-Java interoperability, continue with: + +1. **Advanced Coroutines** โ†’ [Coroutines Introduction](../coroutines/01-introduction.md) +2. **Functional Programming** โ†’ [Lambdas and Higher-Order Functions](../functional-programming/01-lambdas.md) +3. **Collections** โ†’ [Collections Overview](../collections/README.md) +4. **Advanced OOP** โ†’ [Enums and Sealed Classes](../oop/07-enums-sealed-classes.md) + +## ๐Ÿ“š Additional Resources + +- [Official Kotlin-Java Interop Guide](https://kotlinlang.org/docs/java-interop.html) +- [Calling Java from Kotlin](https://kotlinlang.org/docs/java-interop.html#calling-java-code-from-kotlin) +- [Calling Kotlin from Java](https://kotlinlang.org/docs/java-interop.html#calling-kotlin-code-from-java) + +## ๐Ÿ† Summary + +- โœ… You can call Java code from Kotlin seamlessly +- โœ… You know how to use Kotlin code from Java +- โœ… You understand how to handle null safety differences +- โœ… You can work with Java collections and Kotlin collections +- โœ… You're ready to apply best practices for interoperability! + +**Kotlin-Java interoperability is essential for real-world development. Master it for seamless integration with existing Java codebases! ๐ŸŽ‰** diff --git a/docs/basics/01-hello-world.md b/docs/basics/01-hello-world.md new file mode 100644 index 0000000..1d986d2 --- /dev/null +++ b/docs/basics/01-hello-world.md @@ -0,0 +1,206 @@ +# ๐Ÿš€ Hello World - Your First Kotlin Program + +Welcome to Kotlin! This is your first step into the world of Kotlin programming. Let's start with the traditional "Hello World" program. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Write your first Kotlin program +- โœ… Understand the basic structure of a Kotlin application +- โœ… Use the `main` function as the entry point +- โœ… Output text to the console +- โœ… Understand basic syntax and formatting + +## ๐Ÿ” What You'll Learn + +- **Function declaration syntax** - How to create functions in Kotlin +- **Parameter handling** - Understanding the `main` function parameters +- **Basic output operations** - Using `print()` and `println()` +- **Kotlin code structure** - How Kotlin programs are organized + +## ๐Ÿ“ Prerequisites + +**None!** This is your starting point. You don't need any prior programming experience. + +## ๐Ÿ’ป The Code + +Let's look at your first Kotlin program: + +```kotlin +// Hello World App + +fun main(args: Array) { + print("Hello World") +} +``` + +**๐Ÿ“ File:** [01_hello_world.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/01_hello_world.kt) + +## ๐Ÿ” Code Breakdown + +### **Line 1: Comment** +```kotlin +// Hello World App +``` +- `//` indicates a single-line comment +- Comments are ignored by the compiler +- They help explain what your code does + +### **Line 3: Main Function Declaration** +```kotlin +fun main(args: Array) { +``` +- `fun` - Keyword to declare a function +- `main` - Function name (this is special - it's the entry point) +- `args: Array` - Parameter declaration + - `args` - Parameter name + - `Array` - Type (array of strings) +- `{` - Opening brace for function body + +### **Line 4: Function Body** +```kotlin + print("Hello World") +``` +- `print()` - Function to output text without a newline +- `"Hello World"` - String literal (text in quotes) +- `;` - Semicolon is optional in Kotlin (not needed here) + +### **Line 5: Closing Brace** +```kotlin +} +``` +- Closes the function body + +## ๐ŸŽฏ Key Concepts Explained + +### **1. The `main` Function** +- **Entry Point**: Every Kotlin program starts with the `main` function +- **Special Name**: The compiler looks for this specific function +- **Parameters**: `args` contains command-line arguments (we'll use these later) + +### **2. Function Declaration** +```kotlin +fun functionName(parameters): returnType { + // function body +} +``` + +### **3. Output Functions** +- **`print()`**: Outputs text without moving to the next line +- **`println()`**: Outputs text and moves to the next line + +## ๐Ÿงช Running Your First Program + +### **Step 1: Open IntelliJ IDEA** +1. Launch IntelliJ IDEA +2. Open the project folder +3. Navigate to [01_hello_world.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/01_hello_world.kt) + +### **Step 2: Run the Program** +1. Right-click on the file +2. Select "Run '01_hello_worldKt'" +3. Or use the green play button + +### **Step 3: See the Output** +``` +Hello World +``` + +## ๐ŸŽฎ Hands-On Exercises + +### **Exercise 1: Modify the Message** +Change "Hello World" to "Hello Kotlin!" and run the program. + +**Solution:** +```kotlin +fun main(args: Array) { + print("Hello Kotlin!") +} +``` + +### **Exercise 2: Use println()** +Replace `print()` with `println()` and see the difference. + +**Solution:** +```kotlin +fun main(args: Array) { + println("Hello World") +} +``` + +### **Exercise 3: Add Your Name** +Add another print statement with your name. + +**Solution:** +```kotlin +fun main(args: Array) { + print("Hello World") + print("My name is [Your Name]") +} +``` + +### **Exercise 4: Multiple Lines** +Use multiple println statements to create a multi-line output. + +**Solution:** +```kotlin +fun main(args: Array) { + println("Hello World") + println("Welcome to Kotlin") + println("Let's start coding!") +} +``` + +## ๐Ÿ” Understanding the Output + +### **Using `print()`:** +```kotlin +print("Hello") +print("World") +``` +**Output:** `HelloWorld` (no space, no newline) + +### **Using `println()`:** +```kotlin +println("Hello") +println("World") +``` +**Output:** +``` +Hello +World +``` + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Missing quotes**: `print(Hello World)` โŒ + - **Correct**: `print("Hello World")` โœ… + +2. **Missing braces**: `fun main(args: Array) print("Hello")` โŒ + - **Correct**: `fun main(args: Array) { print("Hello") }` โœ… + +3. **Wrong function name**: `fun Main(args: Array)` โŒ + - **Correct**: `fun main(args: Array)` โœ… + +## ๐ŸŽฏ What's Next? + +Congratulations! You've written your first Kotlin program. Now you're ready to: + +1. **Learn about variables** โ†’ [Variables and Data Types](02-variables-data-types.md) +2. **Understand data types** โ†’ [Data Types Deep Dive](04-data-types.md) +3. **Explore more output** โ†’ [Exploring Your First App](../02-explore-first-app.md) + +## ๐Ÿ“š Additional Resources + +- [Official Kotlin Documentation](https://kotlinlang.org/docs/home.html) +- [Kotlin Playground](https://play.kotlinlang.org/) - Try code online +- [IntelliJ IDEA Tutorial](https://www.jetbrains.com/help/idea/creating-and-running-your-first-kotlin-application.html) + +## ๐Ÿ† Summary + +- โœ… You've written your first Kotlin program +- โœ… You understand the basic structure +- โœ… You can output text to the console +- โœ… You're ready to learn more! + +**Keep practicing and happy coding! ๐ŸŽ‰** diff --git a/docs/basics/02-variables-data-types.md b/docs/basics/02-variables-data-types.md new file mode 100644 index 0000000..93f0ced --- /dev/null +++ b/docs/basics/02-variables-data-types.md @@ -0,0 +1,323 @@ +# ๐Ÿ”ค Variables and Data Types in Kotlin + +Welcome to the world of variables and data types! This is where you'll learn how to store and manipulate data in your Kotlin programs. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Declare variables using `var` and `val` +- โœ… Understand the difference between mutable and immutable variables +- โœ… Use type inference to let Kotlin determine types automatically +- โœ… Explicitly declare variable types when needed +- โœ… Work with basic data types: Int, Double, Boolean, String, Char + +## ๐Ÿ” What You'll Learn + +- **Variable declaration** - How to create variables in Kotlin +- **Mutability** - Understanding `var` vs `val` +- **Type inference** - Kotlin's automatic type detection +- **Explicit typing** - When and how to specify types manually +- **Basic data types** - Numbers, text, and logical values + +## ๐Ÿ“ Prerequisites + +- Basic understanding of programming concepts +- Completed [Hello World](01-hello-world.md) lesson + +## ๐Ÿ’ป The Code + +Let's examine the variables and data types example: + +```kotlin +fun main(args: Array) { + // Type inference examples - Kotlin automatically determines the type + var myNumber = 10 // Type: Int + var myDecimal = 1.0 // Type: Double (not Float!) + var isActive = true // Type: Boolean + + // Explicit type declaration + var myString: String // Mutable String with explicit type + myString = "Hello World" + myString = "Another World" // Can change value since it's var + + // Immutable variable using val + val myAnotherString = "My constant string value" // Immutable String + // myAnotherString = "some value" // COMPILE ERROR: Cannot reassign val + + // Best practice: Use val by default, var only when you need mutability + val pi = 3.14159 // Immutable constant + val maxRetries = 3 // Immutable configuration + + // Printing values + println("Number: $myNumber") + println("Decimal: $myDecimal") + println("Is Active: $isActive") + println("String: $myString") + println("Constant: $myAnotherString") + println("Pi: $pi") + println("Max Retries: $maxRetries") +} +``` + +**๐Ÿ“ File:** [04_variables_data_types.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/04_variables_data_types.kt) + +## ๐Ÿ” Code Breakdown + +### **Variable Declaration with Type Inference** + +```kotlin +var myNumber = 10 // Type: Int +var myDecimal = 1.0 // Type: Double +var isActive = true // Type: Boolean +``` + +- **`var`**: Declares a mutable variable (can be changed) +- **Type inference**: Kotlin automatically determines the type based on the value +- **`10`** โ†’ `Int` (32-bit integer) +- **`1.0`** โ†’ `Double` (64-bit floating point) +- **`true`** โ†’ `Boolean` (true/false value) + +### **Explicit Type Declaration** + +```kotlin +var myString: String // Mutable String with explicit type +myString = "Hello World" +myString = "Another World" // Can change value since it's var +``` + +- **`: String`**: Explicitly declares the variable type +- **`var`**: Allows reassignment +- **Multiple assignments**: Can change the value multiple times + +### **Immutable Variables with `val`** + +```kotlin +val myAnotherString = "My constant string value" // Immutable String +// myAnotherString = "some value" // COMPILE ERROR: Cannot reassign val +``` + +- **`val`**: Declares an immutable variable (cannot be changed) +- **Single assignment**: Value is set once and cannot be modified +- **Compile-time safety**: Kotlin prevents accidental reassignment + +## ๐ŸŽฏ Key Concepts Explained + +### **1. Variable Declaration Syntax** + +```kotlin +// Mutable variable +var variableName: Type = value + +// Immutable variable +val constantName: Type = value + +// With type inference +var inferredVariable = value +val inferredConstant = value +``` + +### **2. Mutability: `var` vs `val`** + +| Feature | `var` | `val` | +|---------|-------|-------| +| **Mutability** | Mutable (can change) | Immutable (cannot change) | +| **Reassignment** | โœ… Allowed | โŒ Not allowed | +| **Use case** | When value needs to change | When value should remain constant | +| **Safety** | Less safe | More safe | + +### **3. Type Inference** + +Kotlin automatically determines the type based on the assigned value: + +```kotlin +val number = 42 // Int +val decimal = 3.14 // Double +val text = "Hello" // String +val flag = true // Boolean +val character = 'A' // Char +``` + +### **4. Explicit Type Declaration** + +Sometimes you want to be explicit about types: + +```kotlin +var age: Int = 25 +var name: String = "John" +var height: Double = 1.75 +var isStudent: Boolean = true +``` + +## ๐Ÿ“Š Basic Data Types in Kotlin + +### **Numbers** + +| Type | Size | Range | Example | +|------|------|-------|---------| +| **Byte** | 8 bits | -128 to 127 | `val byte: Byte = 100` | +| **Short** | 16 bits | -32,768 to 32,767 | `val short: Short = 1000` | +| **Int** | 32 bits | -231 to 231-1 | `val int: Int = 1000000` | +| **Long** | 64 bits | -263 to 263-1 | `val long: Long = 1000000000L` | +| **Float** | 32 bits | ยฑ3.4E-38 to ยฑ3.4E+38 | `val float: Float = 3.14f` | +| **Double** | 64 bits | ยฑ1.7E-308 to ยฑ1.7E+308 | `val double: Double = 3.14` | + +### **Text** + +| Type | Description | Example | +|------|-------------|---------| +| **Char** | Single Unicode character | `val char: Char = 'A'` | +| **String** | Sequence of characters | `val string: String = "Hello"` | + +### **Logical** + +| Type | Description | Example | +|------|-------------|---------| +| **Boolean** | true or false | `val boolean: Boolean = true` | + +## ๐Ÿงช Hands-On Exercises + +### **Exercise 1: Create Different Variable Types** +Create variables for your personal information using different data types. + +**Solution:** +```kotlin +fun main(args: Array) { + val name: String = "Your Name" + val age: Int = 25 + val height: Double = 1.75 + val isStudent: Boolean = true + val grade: Char = 'A' + + println("Name: $name") + println("Age: $age") + println("Height: $height") + println("Is Student: $isStudent") + println("Grade: $grade") +} +``` + +### **Exercise 2: Experiment with Mutability** +Create both `var` and `val` variables and try to reassign them. + +**Solution:** +```kotlin +fun main(args: Array) { + var mutableNumber = 10 + val immutableNumber = 20 + + println("Mutable: $mutableNumber") + mutableNumber = 15 // This works + println("Mutable after change: $mutableNumber") + + println("Immutable: $immutableNumber") + // immutableNumber = 25 // This would cause a compile error +} +``` + +### **Exercise 3: Type Inference Challenge** +Let Kotlin infer the types and then verify them. + +**Solution:** +```kotlin +fun main(args: Array) { + val number = 42 + val decimal = 3.14 + val text = "Hello" + val flag = true + + // Kotlin inferred these types automatically + println("Number type: ${number::class.simpleName}") + println("Decimal type: ${decimal::class.simpleName}") + println("Text type: ${text::class.simpleName}") + println("Flag type: ${flag::class.simpleName}") +} +``` + +### **Exercise 4: Calculate with Variables** +Create variables for mathematical calculations. + +**Solution:** +```kotlin +fun main(args: Array) { + val radius: Double = 5.0 + val pi: Double = 3.14159 + + val area = pi * radius * radius + val circumference = 2 * pi * radius + + println("Radius: $radius") + println("Area: $area") + println("Circumference: $circumference") +} +``` + +## ๐Ÿ” Understanding Type Inference + +### **When Type Inference Works Well** + +```kotlin +// Clear and obvious types +val age = 25 // Int +val name = "John" // String +val isActive = true // Boolean +val price = 19.99 // Double +``` + +### **When to Use Explicit Types** + +```kotlin +// Unclear or specific types +val number: Long = 1000000000L +val decimal: Float = 3.14f +val character: Char = 'A' +``` + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Confusing `var` and `val`**: + ```kotlin + val constant = 10 + constant = 20 // โŒ Compile error + ``` + +2. **Type mismatch**: + ```kotlin + var number: Int = "Hello" // โŒ Type mismatch + ``` + +3. **Forgetting quotes for strings**: + ```kotlin + var name = Hello // โŒ Missing quotes + var name = "Hello" // โœ… Correct + ``` + +4. **Using wrong number types**: + ```kotlin + val decimal: Float = 3.14 // โŒ 3.14 is Double by default + val decimal: Float = 3.14f // โœ… Correct + ``` + +## ๐ŸŽฏ What's Next? + +Great job! You've learned about variables and data types. Now you're ready to: + +1. **Explore more data types** โ†’ [Data Types Deep Dive](04-data-types.md) +2. **Learn string operations** โ†’ [String Interpolation](05-string-interpolation.md) +3. **Understand control flow** โ†’ [If Expressions](../control-flow/01-if-expressions.md) +4. **Work with functions** โ†’ [Functions Basics](../functions/01-functions-basics.md) + +## ๐Ÿ“š Additional Resources + +- [Kotlin Data Types Documentation](https://kotlinlang.org/docs/basic-types.html) +- [Kotlin Variables Documentation](https://kotlinlang.org/docs/properties.html) +- [Type Inference in Kotlin](https://kotlinlang.org/docs/type-inference.html) + +## ๐Ÿ† Summary + +- โœ… You can declare variables using `var` and `val` +- โœ… You understand the difference between mutable and immutable +- โœ… You can use type inference and explicit typing +- โœ… You know the basic data types in Kotlin +- โœ… You're ready to work with more complex data structures! + +**Keep practicing and happy coding! ๐ŸŽ‰** diff --git a/docs/basics/03-comments.md b/docs/basics/03-comments.md new file mode 100644 index 0000000..e7bdad1 --- /dev/null +++ b/docs/basics/03-comments.md @@ -0,0 +1,410 @@ +# ๐Ÿ’ฌ Comments and Documentation in Kotlin + +Welcome to the world of code documentation! Comments are essential for making your code readable and maintainable. In this lesson, you'll learn how to write clear, helpful comments in Kotlin. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Write single-line comments using `//` +- โœ… Create multi-line comments using `/* */` +- โœ… Understand when and how to use comments effectively +- โœ… Write self-documenting code +- โœ… Follow Kotlin documentation best practices + +## ๐Ÿ” What You'll Learn + +- **Single-line comments** - Quick explanations for individual lines +- **Multi-line comments** - Detailed explanations for code blocks +- **Documentation comments** - Professional documentation standards +- **Comment best practices** - When and how to comment effectively +- **Self-documenting code** - Writing code that explains itself + +## ๐Ÿ“ Prerequisites + +- Basic understanding of Kotlin syntax +- Completed [Hello World](01-hello-world.md) lesson + +## ๐Ÿ’ป The Code + +Let's examine the comments example: + +```kotlin +/* +* This is comment line 1 +* +* This is comment line 2 +* +* This is main function. Entry point of the application. +* */ + +fun main(args: Array) { // This is inline comment ... + print("Hello World") +} +``` + +**๐Ÿ“ File:** [03_comments.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/03_comments.kt) + +## ๐Ÿ” Code Breakdown + +### **Multi-line Comment Block** + +```kotlin +/* +* This is comment line 1 +* +* This is comment line 2 +* +* This is main function. Entry point of the application. +* */ +``` + +- **`/*`**: Starts a multi-line comment block +- **`*`**: Each line can start with an asterisk for readability +- **`*/`**: Ends the multi-line comment block +- **Purpose**: Explains what the following code does + +### **Single-line Comment** + +```kotlin +fun main(args: Array) { // This is inline comment ... + print("Hello World") +} +``` + +- **`//`**: Starts a single-line comment +- **Inline comment**: Appears on the same line as code +- **Purpose**: Quick explanation of the specific line + +## ๐ŸŽฏ Key Concepts Explained + +### **1. Single-line Comments (`//`)** + +```kotlin +// This is a single-line comment +val name = "John" // This comment explains the variable +val age = 25 // Age in years +``` + +**Use cases:** +- Quick explanations for single lines +- Clarifying complex expressions +- Adding context to variables +- Explaining "why" not "what" + +### **2. Multi-line Comments (`/* */`)** + +```kotlin +/* + * This is a multi-line comment + * It can span multiple lines + * Useful for explaining complex logic + * or documenting functions + */ +fun calculateArea(radius: Double): Double { + return Math.PI * radius * radius +} +``` + +**Use cases:** +- Explaining complex algorithms +- Documenting functions and classes +- Providing context for code blocks +- License information or file headers + +### **3. KDoc Comments (`/** */`)** + +```kotlin +/** + * Calculates the area of a circle + * + * @param radius The radius of the circle + * @return The area of the circle + * @throws IllegalArgumentException if radius is negative + */ +fun calculateArea(radius: Double): Double { + require(radius>= 0) { "Radius cannot be negative" } + return Math.PI * radius * radius +} +``` + +**Use cases:** +- API documentation +- Function and class documentation +- Parameter and return value descriptions +- Exception documentation + +## ๐Ÿงช Hands-On Exercises + +### **Exercise 1: Add Comments to Code** +Add appropriate comments to this code: + +```kotlin +fun main(args: Array) { + val temperature = 25 + val isHot = temperature> 30 + if (isHot) { + println("It's hot today!") + } else { + println("It's not too hot.") + } +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + // Get current temperature in Celsius + val temperature = 25 + + // Check if temperature is considered hot (above 30ยฐC) + val isHot = temperature> 30 + + // Display appropriate message based on temperature + if (isHot) { + println("It's hot today!") + } else { + println("It's not too hot.") + } +} +``` + +### **Exercise 2: Create a Well-Documented Function** +Write a function with comprehensive comments: + +```kotlin +// TODO: Add your solution here +``` + +**Solution:** +```kotlin +/** + * Calculates the grade based on a numerical score + * + * @param score The numerical score (0-100) + * @return The letter grade (A, B, C, D, or F) + * @throws IllegalArgumentException if score is not between 0 and 100 + */ +fun calculateGrade(score: Int): Char { + // Validate input range + require(score in 0..100) { "Score must be between 0 and 100" } + + // Determine grade based on score ranges + return when { + score>= 90 -> 'A' // 90-100: A grade + score>= 80 -> 'B' // 80-89: B grade + score>= 70 -> 'C' // 70-79: C grade + score>= 60 -> 'D' // 60-69: D grade + else -> 'F' // 0-59: F grade + } +} +``` + +### **Exercise 3: Comment Types Practice** +Create examples of all three comment types: + +```kotlin +// TODO: Add your solution here +``` + +**Solution:** +```kotlin +// Single-line comment: This function calculates the factorial +fun factorial(n: Int): Int { + /* + * Multi-line comment: + * This function uses recursion to calculate factorial + * Factorial of n = n * (n-1) * (n-2) * ... * 1 + */ + + /** + * KDoc comment: + * Calculates the factorial of a non-negative integer + * + * @param n The number to calculate factorial for + * @return The factorial of n + * @throws IllegalArgumentException if n is negative + */ + + require(n>= 0) { "Factorial is not defined for negative numbers" } + + return if (n <= 1) 1 else n * factorial(n - 1) +} +``` + +## ๐Ÿ” Comment Best Practices + +### **โœ… Do's** + +1. **Explain "why" not "what"**: + ```kotlin + // Good: Explains the reasoning + val timeout = 5000 // 5 seconds timeout for network operations + + // Bad: Obvious from code + val timeout = 5000 // Sets timeout to 5000 + ``` + +2. **Keep comments up-to-date**: + ```kotlin + // Update this comment when you change the logic + val maxRetries = 3 // Maximum number of retry attempts + ``` + +3. **Use clear, concise language**: + ```kotlin + // Good: Clear and specific + val bufferSize = 1024 // Buffer size optimized for 4K displays + + // Bad: Vague and unhelpful + val bufferSize = 1024 // Some buffer size + ``` + +### **โŒ Don'ts** + +1. **Don't comment obvious code**: + ```kotlin + // Bad: Comment adds no value + val name = "John" // Assigns "John" to name variable + + // Good: No comment needed + val name = "John" + ``` + +2. **Don't leave outdated comments**: + ```kotlin + // Bad: Comment is wrong + val maxUsers = 100 // Maximum 50 users allowed + + // Good: Comment matches code + val maxUsers = 100 // Maximum 100 users allowed + ``` + +3. **Don't use comments to fix bad code**: + ```kotlin + // Bad: Comment tries to explain confusing code + val x = a + b * c // Add a to the product of b and c + + // Good: Self-documenting code + val result = a + (b * c) + ``` + +## ๐ŸŽฏ When to Use Comments + +### **โœ… Good Times to Comment** + +1. **Complex algorithms** - Explain the logic step by step +2. **Business rules** - Document why certain decisions are made +3. **Workarounds** - Explain temporary solutions or known issues +4. **API usage** - Document how to use your functions +5. **Non-obvious code** - Explain code that isn't self-explanatory + +### **โŒ Avoid Commenting** + +1. **Obvious code** - Code that explains itself +2. **Temporary code** - Code that will be removed +3. **Bad code** - Fix the code instead of explaining it +4. **Implementation details** - Focus on what and why, not how + +## ๐Ÿ” Self-Documenting Code Examples + +### **Instead of Comments, Use Better Names** + +```kotlin +// Bad: Needs comment to explain +val x = 86400000 // Milliseconds in a day + +// Good: Self-documenting +val millisecondsInDay = 86400000 +``` + +### **Use Constants for Magic Numbers** + +```kotlin +// Bad: Magic number with comment +if (score>= 90) { // 90 is the threshold for A grade + grade = 'A' +} + +// Good: Named constant +const val A_GRADE_THRESHOLD = 90 +if (score>= A_GRADE_THRESHOLD) { + grade = 'A' +} +``` + +### **Break Complex Logic into Functions** + +```kotlin +// Bad: Complex logic with comments +fun processUser(user: User) { + // Check if user is eligible for premium features + if (user.age>= 18 && user.subscriptionType == "premium" && user.paymentStatus == "active") { + // Enable premium features + enablePremiumFeatures(user) + } +} + +// Good: Self-documenting functions +fun processUser(user: User) { + if (isEligibleForPremium(user)) { + enablePremiumFeatures(user) + } +} + +private fun isEligibleForPremium(user: User): Boolean { + return user.age>= 18 && + user.subscriptionType == "premium" && + user.paymentStatus == "active" +} +``` + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Commenting obvious code**: + ```kotlin + val name = "John" // Sets name to John โŒ + ``` + +2. **Outdated comments**: + ```kotlin + val maxUsers = 100 // Maximum 50 users โŒ + ``` + +3. **Using comments to explain bad code**: + ```kotlin + // This is a hack because the API is broken โŒ + val result = hackyWorkaround() + ``` + +4. **Too many comments**: + ```kotlin + // Get the name + val name = getName() + // Print the name + println(name) โŒ + ``` + +## ๐ŸŽฏ What's Next? + +Excellent! You've learned about comments and documentation. Now you're ready to: + +1. **Explore data types** โ†’ [Data Types Deep Dive](04-data-types.md) +2. **Learn string operations** โ†’ [String Interpolation](05-string-interpolation.md) +3. **Understand control flow** โ†’ [If Expressions](../control-flow/01-if-expressions.md) +4. **Work with functions** โ†’ [Functions Basics](../functions/01-functions-basics.md) + +## ๐Ÿ“š Additional Resources + +- [Kotlin Documentation](https://kotlinlang.org/docs/kotlin-doc.html) +- [KDoc Reference](https://kotlinlang.org/docs/kotlin-doc.html) +- [Comment Best Practices](https://blog.jetbrains.com/kotlin/2019/02/kotlin-1-3-50-released/) + +## ๐Ÿ† Summary + +- โœ… You can write single-line and multi-line comments +- โœ… You understand when and how to use comments effectively +- โœ… You know how to write self-documenting code +- โœ… You follow Kotlin documentation best practices +- โœ… You're ready to write clear, maintainable code! + +**Keep practicing and happy coding! ๐ŸŽ‰** diff --git a/docs/basics/04-data-types.md b/docs/basics/04-data-types.md new file mode 100644 index 0000000..c181042 --- /dev/null +++ b/docs/basics/04-data-types.md @@ -0,0 +1,409 @@ +# ๐Ÿ”ข Data Types Deep Dive in Kotlin + +Welcome to the comprehensive guide to data types in Kotlin! In this lesson, you'll explore all the fundamental data types, their characteristics, and how to use them effectively in your programs. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Understand all basic data types in Kotlin +- โœ… Choose the right data type for your needs +- โœ… Work with numbers, text, and logical values +- โœ… Understand type conversion and casting +- โœ… Use data types efficiently in your programs + +## ๐Ÿ” What You'll Learn + +- **Number types** - Integers, floating-point numbers, and their ranges +- **Text types** - Characters and strings +- **Logical types** - Boolean values +- **Type conversion** - Converting between different types +- **Type safety** - How Kotlin ensures type safety + +## ๐Ÿ“ Prerequisites + +- Basic understanding of variables +- Completed [Variables and Data Types](02-variables-data-types.md) lesson + +## ๐Ÿ’ป The Code + +Let's examine the data types example: + +```kotlin +fun main(args: Array) { + var name: String + name = "Kevin" + + var age: Int = 10 + var myAge = 10 + + var isAlive: Boolean = true + var marks: Float = 97.4F + var percentage: Double = 90.78 + var gender: Char = 'M' + + print(marks) +} +``` + +**๐Ÿ“ File:** [07_data_types.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/07_data_types.kt) + +## ๐Ÿ” Code Breakdown + +### **String Type** + +```kotlin +var name: String +name = "Kevin" +``` + +- **`String`**: Represents a sequence of characters +- **`"Kevin"`**: String literal (text in double quotes) +- **Mutable**: Can be changed since it's declared with `var` + +### **Integer Types** + +```kotlin +var age: Int = 10 +var myAge = 10 +``` + +- **`Int`**: 32-bit integer type +- **`10`**: Integer literal +- **Type inference**: `myAge` automatically becomes `Int` + +### **Boolean Type** + +```kotlin +var isAlive: Boolean = true +``` + +- **`Boolean`**: Represents true or false values +- **`true`**: Boolean literal +- **Use case**: Logical conditions and flags + +### **Floating-Point Types** + +```kotlin +var marks: Float = 97.4F +var percentage: Double = 90.78 +``` + +- **`Float`**: 32-bit floating-point number +- **`Double`**: 64-bit floating-point number (default for decimals) +- **`97.4F`**: Float literal (note the `F` suffix) +- **`90.78`**: Double literal (default type for decimal numbers) + +### **Character Type** + +```kotlin +var gender: Char = 'M' +``` + +- **`Char`**: Represents a single Unicode character +- **`'M'`**: Character literal (single quotes) + +## ๐ŸŽฏ Key Concepts Explained + +### **1. Number Types in Detail** + +#### **Integer Types** + +| Type | Size | Range | Suffix | Example | +|------|------|-------|--------|---------| +| **Byte** | 8 bits | -128 to 127 | None | `val byte: Byte = 100` | +| **Short** | 16 bits | -32,768 to 32,767 | None | `val short: Short = 1000` | +| **Int** | 32 bits | -231 to 231-1 | None | `val int: Int = 1000000` | +| **Long** | 64 bits | -263 to 263-1 | `L` or `l` | `val long: Long = 1000000000L` | + +**When to use each:** +- **`Byte`**: Very small numbers, memory optimization +- **`Short`**: Small numbers, legacy APIs +- **`Int`**: General-purpose integers (default choice) +- **`Long`**: Large numbers, timestamps, IDs + +#### **Floating-Point Types** + +| Type | Size | Precision | Suffix | Example | +|------|------|-----------|--------|---------| +| **Float** | 32 bits | 6-7 digits | `F` or `f` | `val float: Float = 3.14f` | +| **Double** | 64 bits | 15-17 digits | None | `val double: Double = 3.14` | + +**When to use each:** +- **`Float`**: Memory optimization, sufficient precision +- **`Double`**: High precision, default for decimal numbers + +### **2. Text Types** + +#### **Character (`Char`)** + +```kotlin +val letter: Char = 'A' +val digit: Char = '5' +val symbol: Char = '$' +val unicode: Char = '\u0041' // Unicode for 'A' +``` + +**Characteristics:** +- Single Unicode character +- 16-bit Unicode value +- Single quotes required +- Can represent any Unicode character + +#### **String** + +```kotlin +val name: String = "John Doe" +val empty: String = "" +val multiline: String = """ + This is a + multi-line string +""" +``` + +**Characteristics:** +- Sequence of characters +- Immutable (cannot be changed) +- Double quotes required +- Rich set of methods and properties + +### **3. Boolean Type** + +```kotlin +val isActive: Boolean = true +val isComplete: Boolean = false +val isValid: Boolean = (age>= 18) +``` + +**Use cases:** +- Conditional statements +- Flags and status indicators +- Logical operations +- Control flow decisions + +## ๐Ÿงช Hands-On Exercises + +### **Exercise 1: Type Declaration Practice** +Create variables of different types and observe type inference: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + // Explicit type declarations + val age: Int = 25 + val height: Double = 1.75 + val isStudent: Boolean = true + val grade: Char = 'A' + val name: String = "Alice" + + // Type inference examples + val temperature = 23.5 // Double (default for decimals) + val year = 2024 // Int + val message = "Hello" // String + val flag = false // Boolean + + // Print types to verify + println("Age type: ${age::class.simpleName}") + println("Height type: ${height::class.simpleName}") + println("Temperature type: ${temperature::class.simpleName}") +} +``` + +### **Exercise 2: Number Type Limits** +Explore the limits of different number types: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + // Byte limits + val maxByte: Byte = Byte.MAX_VALUE + val minByte: Byte = Byte.MIN_VALUE + println("Byte range: $minByte to $maxByte") + + // Int limits + val maxInt: Int = Int.MAX_VALUE + val minInt: Int = Int.MIN_VALUE + println("Int range: $minInt to $maxInt") + + // Long limits + val maxLong: Long = Long.MAX_VALUE + val minLong: Long = Long.MIN_VALUE + println("Long range: $minLong to $maxLong") + + // Float vs Double precision + val floatValue: Float = 3.14159265359f + val doubleValue: Double = 3.14159265359 + println("Float: $floatValue") + println("Double: $doubleValue") +} +``` + +### **Exercise 3: Type Conversion** +Practice converting between different types: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val intValue = 42 + val doubleValue = 3.14 + + // Int to other types + val longFromInt: Long = intValue.toLong() + val floatFromInt: Float = intValue.toFloat() + val doubleFromInt: Double = intValue.toDouble() + + // Double to other types + val intFromDouble: Int = doubleValue.toInt() // Truncates decimal part + val floatFromDouble: Float = doubleValue.toFloat() + val longFromDouble: Long = doubleValue.toLong() + + // String conversions + val stringFromInt = intValue.toString() + val intFromString = "123".toInt() + + println("Original int: $intValue") + println("As long: $longFromInt") + println("As float: $floatFromInt") + println("As double: $doubleFromInt") + println("As string: $stringFromInt") +} +``` + +### **Exercise 4: Practical Data Types** +Create a student information system using appropriate data types: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + // Student information with appropriate types + val studentId: Long = 2024001L // Long for large ID numbers + val firstName: String = "John" + val lastName: String = "Doe" + val age: Int = 20 // Int for age + val height: Double = 1.75 // Double for precise height + val weight: Float = 70.5f // Float for weight + val grade: Char = 'A' // Char for single grade + val isEnrolled: Boolean = true // Boolean for enrollment status + val gpa: Double = 3.85 // Double for precise GPA + + // Display student information + println("Student ID: $studentId") + println("Name: $firstName $lastName") + println("Age: $age years") + println("Height: ${height}m") + println("Weight: ${weight}kg") + println("Grade: $grade") + println("Enrolled: $isEnrolled") + println("GPA: $gpa") + + // Calculate age in months + val ageInMonths: Int = age * 12 + println("Age in months: $ageInMonths") +} +``` + +## ๐Ÿ” Type Conversion and Casting + +### **Implicit Conversion (Automatic)** + +Kotlin automatically converts smaller types to larger types: + +```kotlin +val intValue: Int = 42 +val longValue: Long = intValue // Automatic conversion Int โ†’ Long +val doubleValue: Double = intValue // Automatic conversion Int โ†’ Double +``` + +### **Explicit Conversion (Manual)** + +Use conversion functions for potentially lossy conversions: + +```kotlin +val doubleValue: Double = 3.14 +val intValue: Int = doubleValue.toInt() // Truncates to 3 +val longValue: Long = doubleValue.toLong() // Truncates to 3 +``` + +### **Safe Conversion Functions** + +```kotlin +val stringNumber = "123" +val intNumber = stringNumber.toIntOrNull() // Returns null if conversion fails +val longNumber = stringNumber.toLongOrNull() +val doubleNumber = stringNumber.toDoubleOrNull() +``` + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Type mismatch errors**: + ```kotlin + val age: Int = "25" // โŒ Type mismatch + val age: Int = 25 // โœ… Correct + ``` + +2. **Forgetting suffixes for specific types**: + ```kotlin + val floatValue: Float = 3.14 // โŒ 3.14 is Double by default + val floatValue: Float = 3.14f // โœ… Correct + ``` + +3. **Using wrong number types**: + ```kotlin + val largeNumber: Int = 3000000000 // โŒ Too large for Int + val largeNumber: Long = 3000000000L // โœ… Correct + ``` + +4. **Character vs String confusion**: + ```kotlin + val letter: Char = "A" // โŒ Double quotes for String + val letter: Char = 'A' // โœ… Single quotes for Char + ``` + +## ๐ŸŽฏ What's Next? + +Excellent! You've mastered data types in Kotlin. Now you're ready to: + +1. **Learn string operations** โ†’ [String Interpolation](05-string-interpolation.md) +2. **Understand control flow** โ†’ [If Expressions](../control-flow/01-if-expressions.md) +3. **Work with functions** โ†’ [Functions Basics](../functions/01-functions-basics.md) +4. **Explore collections** โ†’ [Arrays](../collections/01-arrays.md) + +## ๐Ÿ“š Additional Resources + +- [Kotlin Basic Types](https://kotlinlang.org/docs/basic-types.html) +- [Number Types](https://kotlinlang.org/docs/numbers.html) +- [Strings](https://kotlinlang.org/docs/strings.html) +- [Type Conversion](https://kotlinlang.org/docs/numbers.html#explicit-conversions) + +## ๐Ÿ† Summary + +- โœ… You understand all basic data types in Kotlin +- โœ… You can choose the right data type for your needs +- โœ… You know how to work with numbers, text, and logical values +- โœ… You understand type conversion and casting +- โœ… You can use data types efficiently in your programs! + +**Keep practicing and happy coding! ๐ŸŽ‰** diff --git a/docs/basics/05-string-interpolation.md b/docs/basics/05-string-interpolation.md new file mode 100644 index 0000000..290a4de --- /dev/null +++ b/docs/basics/05-string-interpolation.md @@ -0,0 +1,380 @@ +# ๐Ÿ”ค String Interpolation in Kotlin + +Welcome to the world of string interpolation! This powerful feature allows you to embed variables and expressions directly into strings, making your code more readable and maintainable. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Use string interpolation with the `$` symbol +- โœ… Embed variables and expressions in strings +- โœ… Format complex expressions with `${}` syntax +- โœ… Create dynamic and readable string output +- โœ… Understand when and how to use string interpolation + +## ๐Ÿ” What You'll Learn + +- **Basic interpolation** - Embedding simple variables in strings +- **Expression interpolation** - Using complex expressions with `${}` +- **Formatting** - Controlling how values are displayed +- **Best practices** - When and how to use interpolation effectively +- **Performance considerations** - Understanding interpolation overhead + +## ๐Ÿ“ Prerequisites + +- Basic understanding of variables and data types +- Completed [Data Types Deep Dive](04-data-types.md) lesson + +## ๐Ÿ’ป The Code + +Let's examine the string interpolation example: + +```kotlin +fun main(args: Array) { + var rect = Rectangle() + rect.length = 5 + rect.breadth = 3 + + print("The length of the rectangle is ${rect.length} and breadth is ${rect.breadth}. The area is ${rect.length * rect.breadth}") +} + +class Rectangle { + var length: Int = 0 + var breadth: Int = 0 +} +``` + +**๐Ÿ“ File:** [08_string_interpolation.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/08_string_interpolation.kt) + +## ๐Ÿ” Code Breakdown + +### **Rectangle Class** + +```kotlin +class Rectangle { + var length: Int = 0 + var breadth: Int = 0 +} +``` + +- **Simple class** with two properties +- **`length`** and **`breadth`** represent rectangle dimensions +- **Default values** of 0 for both properties + +### **String Interpolation Usage** + +```kotlin +print("The length of the rectangle is ${rect.length} and breadth is ${rect.breadth}. The area is ${rect.length * rect.breadth}") +``` + +- **`${rect.length}`**: Embeds the length value +- **`${rect.breadth}`**: Embeds the breadth value +- **`${rect.length * rect.breadth}`**: Embeds the calculated area + +## ๐ŸŽฏ Key Concepts Explained + +### **1. Basic String Interpolation** + +#### **Simple Variable Interpolation** + +```kotlin +val name = "John" +val age = 25 +val message = "Hello, my name is $name and I am $age years old" +println(message) +// Output: Hello, my name is John and I am 25 years old +``` + +**Syntax:** +- **`$variableName`**: Embeds a simple variable +- **No spaces**: Variable name must immediately follow `$` +- **Simple types**: Works with strings, numbers, booleans + +#### **Expression Interpolation** + +```kotlin +val a = 10 +val b = 5 +val result = "Sum: ${a + b}, Product: ${a * b}, Difference: ${a - b}" +println(result) +// Output: Sum: 15, Product: 50, Difference: 5 +``` + +**Syntax:** +- **`${expression}`**: Embeds any valid Kotlin expression +- **Curly braces**: Required for complex expressions +- **Arithmetic**: Can include calculations, function calls, etc. + +### **2. When to Use Each Syntax** + +#### **Use `$variable` for:** +- Simple variable names +- Properties without spaces +- Basic values + +```kotlin +val name = "Alice" +val greeting = "Hello $name!" // โœ… Simple variable +``` + +#### **Use `${expression}` for:** +- Complex expressions +- Function calls +- Calculations +- Properties with spaces +- Any expression that needs evaluation + +```kotlin +val firstName = "John" +val lastName = "Doe" +val fullName = "${firstName} ${lastName}" // โœ… Expression with spaces + +val radius = 5.0 +val area = "Area: ${Math.PI * radius * radius}" // โœ… Complex calculation +``` + +### **3. Advanced Interpolation Examples** + +#### **Function Calls in Interpolation** + +```kotlin +fun getCurrentTime(): String = "12:00 PM" + +val message = "Current time is ${getCurrentTime()}" +println(message) +// Output: Current time is 12:00 PM +``` + +#### **Conditional Expressions** + +```kotlin +val score = 85 +val grade = "Your grade is ${if (score>= 90) 'A' else if (score>= 80) 'B' else 'C'}" +println(grade) +// Output: Your grade is B +``` + +#### **Object Properties** + +```kotlin +data class Person(val name: String, val age: Int) + +val person = Person("Bob", 30) +val info = "Person: ${person.name}, Age: ${person.age}" +println(info) +// Output: Person: Bob, Age: 30 +``` + +## ๐Ÿงช Hands-On Exercises + +### **Exercise 1: Basic String Interpolation** +Create a program that uses string interpolation to display personal information: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val name = "Alice" + val age = 25 + val city = "New York" + val profession = "Software Developer" + + val bio = "Hi, I'm $name, a $age-year-old $profession from $city." + println(bio) + + // Using expressions + val birthYear = 2024 - age + val message = "I was born in $birthYear and have been coding for ${age - 18} years." + println(message) +} +``` + +### **Exercise 2: Mathematical Expressions** +Create a calculator that displays results using string interpolation: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val a = 15 + val b = 7 + + println("Numbers: $a and $b") + println("Sum: ${a + b}") + println("Difference: ${a - b}") + println("Product: ${a * b}") + println("Quotient: ${a / b}") + println("Remainder: ${a % b}") + println("Power: ${a.toDouble().pow(b.toDouble())}") + + // Calculate average + val average = (a + b) / 2.0 + println("Average: $average") +} +``` + +### **Exercise 3: Complex Object Interpolation** +Create a product catalog using string interpolation: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +data class Product(val name: String, val price: Double, val category: String) + +fun main(args: Array) { + val products = listOf( + Product("Laptop", 999.99, "Electronics"), + Product("Book", 19.99, "Education"), + Product("Coffee", 4.99, "Beverages") + ) + + for (product in products) { + val description = """ + Product: ${product.name} + Price: $${product.price} + Category: ${product.category} + Tax (8%): $${product.price * 0.08} + Total: $${product.price * 1.08} + """.trimIndent() + + println(description) + println("---") + } +} +``` + +### **Exercise 4: Dynamic Messages** +Create a weather app that generates dynamic messages: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val temperature = 28 + val humidity = 65 + val isRaining = false + + val weatherMessage = """ + ๐ŸŒค๏ธ Weather Report + Temperature: ${temperature}ยฐC + Humidity: ${humidity}% + Conditions: ${if (isRaining) "Rainy" else "Clear"} + + ${when { + temperature> 30 -> "It's hot today! Stay hydrated." + temperature> 20 -> "Pleasant weather for outdoor activities." + temperature> 10 -> "Cool weather, bring a light jacket." + else -> "Cold weather, dress warmly." + }} + + ${if (humidity> 70) "High humidity - expect muggy conditions." else "Comfortable humidity levels."} + """.trimIndent() + + println(weatherMessage) +} +``` + +## ๐Ÿ” String Interpolation vs String Concatenation + +### **String Interpolation (Recommended)** + +```kotlin +val name = "John" +val age = 25 +val message = "Hello $name, you are $age years old" +``` + +**Advantages:** +- โœ… More readable +- โœ… Less error-prone +- โœ… Better performance +- โœ… Cleaner syntax + +### **String Concatenation (Old Way)** + +```kotlin +val name = "John" +val age = 25 +val message = "Hello " + name + ", you are " + age + " years old" +``` + +**Disadvantages:** +- โŒ Harder to read +- โŒ More error-prone +- โŒ Poorer performance +- โŒ Verbose syntax + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Missing curly braces for expressions**: + ```kotlin + val a = 5 + val b = 3 + val result = "Sum: $a + b" // โŒ Output: Sum: 5 + b + val result = "Sum: ${a + b}" // โœ… Output: Sum: 8 + ``` + +2. **Using `$` in regular strings**: + ```kotlin + val price = 100 + val message = "Price: $price" // โŒ Won't work if you want literal $ + val message = "Price: \$$price" // โœ… Escapes the $ symbol + ``` + +3. **Complex expressions without braces**: + ```kotlin + val name = "John" + val message = "Hello $name.toUpperCase()" // โŒ Won't work + val message = "Hello ${name.uppercase()}" // โœ… Correct + ``` + +4. **Forgetting to import functions**: + ```kotlin + val result = "Power: ${Math.pow(2.0, 3.0)}" // โŒ Math not imported + import kotlin.math.pow + val result = "Power: ${2.0.pow(3.0)}" // โœ… Correct + ``` + +## ๐ŸŽฏ What's Next? + +Excellent! You've mastered string interpolation in Kotlin. Now you're ready to: + +1. **Learn control flow** โ†’ [If Expressions](../control-flow/01-if-expressions.md) +2. **Understand loops** โ†’ [For Loops](../control-flow/03-for-loops.md) +3. **Work with functions** โ†’ [Functions Basics](../functions/01-functions-basics.md) +4. **Explore collections** โ†’ [Arrays](../collections/01-arrays.md) + +## ๐Ÿ“š Additional Resources + +- [Kotlin Strings](https://kotlinlang.org/docs/strings.html) +- [String Templates](https://kotlinlang.org/docs/strings.html#string-templates) +- [String Formatting](https://kotlinlang.org/docs/strings.html#string-templates) + +## ๐Ÿ† Summary + +- โœ… You can use string interpolation with the `$` symbol +- โœ… You can embed variables and expressions in strings +- โœ… You understand when to use `${}` vs `$` +- โœ… You can create dynamic and readable string output +- โœ… You know the best practices for string interpolation! + +**Keep practicing and happy coding! ๐ŸŽ‰** diff --git a/docs/collections/01-arrays.md b/docs/collections/01-arrays.md new file mode 100644 index 0000000..51b149a --- /dev/null +++ b/docs/collections/01-arrays.md @@ -0,0 +1,270 @@ +# ๐Ÿ“š Arrays in Kotlin + +Arrays are one of the fundamental collection types in Kotlin. They store multiple values of the same type in a fixed-size, ordered collection. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Create and initialize arrays in different ways +- โœ… Access and modify array elements +- โœ… Use array properties and methods +- โœ… Understand array limitations and when to use them +- โœ… Work with different data types in arrays + +## ๐Ÿ” What You'll Learn + +- **Array creation** - Different ways to create arrays +- **Element access** - How to read and write array elements +- **Array properties** - Size, indices, and other useful properties +- **Array methods** - Built-in functions for array manipulation +- **Type safety** - How Kotlin ensures type consistency + +## ๐Ÿ“ Prerequisites + +- Basic understanding of [variables and data types](../basics/02-variables-data-types.md) +- Knowledge of [control flow](../control-flow/01-if-expressions.md) +- Familiarity with [functions](../functions/01-functions-basics.md) + +## ๐Ÿ’ป The Code + +Let's examine the arrays example: + +**๐Ÿ“ File:** [40_arrays.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/40_arrays.kt) + +## ๐Ÿ” Code Breakdown + +### **1. Array Creation** + +#### **Using `arrayOf()`** +```kotlin +val numbers = arrayOf(1, 2, 3, 4, 5) +val names = arrayOf("Alice", "Bob", "Charlie") +val mixed = arrayOf(1, "Hello", 3.14, true) +``` + +#### **Using `Array()` Constructor** +```kotlin +val squares = Array(5) { i -> i * i } // [0, 1, 4, 9, 16] +val zeros = Array(3) { 0 } // [0, 0, 0] +``` + +#### **Type-Specific Arrays** +```kotlin +val intArray = intArrayOf(1, 2, 3, 4, 5) +val doubleArray = doubleArrayOf(1.1, 2.2, 3.3) +val charArray = charArrayOf('a', 'b', 'c') +``` + +### **2. Accessing Array Elements** + +#### **Index-based Access** +```kotlin +val numbers = arrayOf(10, 20, 30, 40, 50) +val first = numbers[0] // 10 +val third = numbers[2] // 30 +val last = numbers[4] // 50 +``` + +#### **Safe Access with `get()`** +```kotlin +val numbers = arrayOf(10, 20, 30, 40, 50) +val element = numbers.get(2) // 30 +``` + +### **3. Modifying Array Elements** + +```kotlin +val numbers = arrayOf(1, 2, 3, 4, 5) +numbers[0] = 100 // Direct assignment +numbers.set(1, 200) // Using set() method +// Result: [100, 200, 3, 4, 5] +``` + +### **4. Array Properties** + +```kotlin +val numbers = arrayOf(1, 2, 3, 4, 5) +println("Size: ${numbers.size}") // 5 +println("Indices: ${numbers.indices}") // 0..4 +println("Last index: ${numbers.lastIndex}") // 4 +``` + +### **5. Iterating Through Arrays** + +#### **Using for loop with indices** +```kotlin +val numbers = arrayOf(10, 20, 30, 40, 50) +for (i in numbers.indices) { + println("Index $i: ${numbers[i]}") +} +``` + +#### **Using for-each loop** +```kotlin +val numbers = arrayOf(10, 20, 30, 40, 50) +for (number in numbers) { + println("Number: $number") +} +``` + +#### **Using forEach function** +```kotlin +val numbers = arrayOf(10, 20, 30, 40, 50) +numbers.forEach { number -> + println("Number: $number") +} +``` + +## ๐ŸŽฏ Key Concepts Explained + +### **1. Array Characteristics** +- **Fixed Size**: Once created, array size cannot change +- **Ordered**: Elements maintain their position +- **Indexed**: Access elements using zero-based indices +- **Type Consistent**: All elements must be of the same type + +### **2. Array vs List** +```kotlin +// Array - fixed size, mutable +val array = arrayOf(1, 2, 3) +array[0] = 10 // โœ… Can modify + +// List - dynamic size, immutable by default +val list = listOf(1, 2, 3) +// list[0] = 10 // โŒ Compilation error +``` + +### **3. Array Bounds** +```kotlin +val numbers = arrayOf(1, 2, 3, 4, 5) +// Valid indices: 0, 1, 2, 3, 4 +// numbers[5] // โŒ ArrayIndexOutOfBoundsException +// numbers[-1] // โŒ ArrayIndexOutOfBoundsException +``` + +## ๐Ÿงช Running the Examples + +### **Step 1: Open the File** +1. Navigate to `src/40_arrays.kt` +2. Open it in IntelliJ IDEA + +### **Step 2: Run the Program** +1. Right-click on the file +2. Select "Run '40_arraysKt'" +3. Observe the output + +## ๐ŸŽฎ Hands-On Exercises + +### **Exercise 1: Create and Modify Arrays** +Create an array of your favorite colors and change the second color. + +**Solution:** +```kotlin +fun main() { + val colors = arrayOf("Red", "Blue", "Green", "Yellow") + println("Original: ${colors.joinToString()}") + + colors[1] = "Purple" + println("Modified: ${colors.joinToString()}") +} +``` + +### **Exercise 2: Find Maximum Value** +Write a function to find the maximum value in an array of numbers. + +**Solution:** +```kotlin +fun findMax(numbers: Array): Int { + var max = numbers[0] + for (i in 1 until numbers.size) { + if (numbers[i]> max) { + max = numbers[i] + } + } + return max +} + +fun main() { + val numbers = arrayOf(23, 45, 12, 67, 34) + println("Maximum: ${findMax(numbers)}") +} +``` + +### **Exercise 3: Reverse Array** +Create a function to reverse the elements of an array. + +**Solution:** +```kotlin +fun reverseArray(numbers: Array): Array { + val reversed = Array(numbers.size) { 0 } + for (i in numbers.indices) { + reversed[i] = numbers[numbers.lastIndex - i] + } + return reversed +} + +fun main() { + val numbers = arrayOf(1, 2, 3, 4, 5) + val reversed = reverseArray(numbers) + println("Original: ${numbers.joinToString()}") + println("Reversed: ${reversed.joinToString()}") +} +``` + +### **Exercise 4: Array Statistics** +Calculate the sum, average, and count of even numbers in an array. + +**Solution:** +```kotlin +fun analyzeArray(numbers: Array) { + val sum = numbers.sum() + val average = sum.toDouble() / numbers.size + val evenCount = numbers.count { it % 2 == 0 } + + println("Sum: $sum") + println("Average: $average") + println("Even numbers: $evenCount") +} + +fun main() { + val numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + analyzeArray(numbers) +} +``` + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Array bounds error**: `array[array.size]` โŒ + - **Correct**: `array[array.lastIndex]` โœ… + +2. **Type mismatch**: `arrayOf(1, "hello", 3.14)` โŒ + - **Correct**: Use specific types or `Array` โœ… + +3. **Modifying immutable arrays**: `arrayOf(1, 2, 3)[0] = 10` โŒ + - **Correct**: Store in variable first โœ… + +4. **Forgetting zero-based indexing**: `array[1]` is second element โœ… + +## ๐ŸŽฏ What's Next? + +Now that you understand arrays, continue with: + +1. **Lists** โ†’ [Lists and Collections](02-lists.md) +2. **Maps** โ†’ [Maps and HashMaps](03-maps.md) +3. **Sets** โ†’ [Sets and HashSets](04-sets.md) +4. **Functional operations** โ†’ [Filter, Map, and Sorting](05-filter-map-sorting.md) + +## ๐Ÿ“š Additional Resources + +- [Official Kotlin Arrays Documentation](https://kotlinlang.org/docs/arrays.html) +- [Kotlin Collections Overview](https://kotlinlang.org/docs/collections-overview.html) +- [Array Methods Reference](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/) + +## ๐Ÿ† Summary + +- โœ… You can create arrays using different methods +- โœ… You understand how to access and modify elements +- โœ… You know array properties and iteration methods +- โœ… You're ready to work with more complex collections! + +**Arrays are the foundation of collections in Kotlin. Master them well! ๐ŸŽ‰** diff --git a/docs/collections/02-lists.md b/docs/collections/02-lists.md new file mode 100644 index 0000000..c31ac52 --- /dev/null +++ b/docs/collections/02-lists.md @@ -0,0 +1,351 @@ +# ๐Ÿ“š Lists in Kotlin + +Lists are one of the most commonly used collection types in Kotlin. Unlike arrays, lists can grow or shrink dynamically and provide many useful methods for manipulation. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Create and initialize lists in different ways +- โœ… Understand the difference between immutable and mutable lists +- โœ… Add, remove, and modify list elements +- โœ… Use list methods for searching, filtering, and transformation +- โœ… Work with list indices and ranges + +## ๐Ÿ” What You'll Learn + +- **List creation** - Different ways to create lists +- **Immutability vs Mutability** - Understanding `List` vs `MutableList` +- **Element manipulation** - Adding, removing, and updating elements +- **List methods** - Built-in functions for list operations +- **Functional operations** - Using lambdas with lists + +## ๐Ÿ“ Prerequisites + +- Understanding of [Arrays](01-arrays.md) +- Knowledge of [Functions](../functions/01-functions-basics.md) +- Familiarity with [Control Flow](../control-flow/01-if-expressions.md) + +## ๐Ÿ’ป The Code + +Let's examine the lists example: + +**๐Ÿ“ File:** [41_list.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/41_list.kt) + +## ๐Ÿ” Code Breakdown + +### **1. List Creation** + +#### **Immutable Lists with `listOf()`** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5) +val names = listOf("Alice", "Bob", "Charlie") +val empty = listOf() // Empty list with explicit type +``` + +#### **Mutable Lists with `mutableListOf()`** +```kotlin +val mutableNumbers = mutableListOf(1, 2, 3, 4, 5) +val mutableNames = mutableListOf("Alice", "Bob", "Charlie") +``` + +#### **Using `List()` Constructor** +```kotlin +val squares = List(5) { i -> i * i } // [0, 1, 4, 9, 16] +val repeated = List(3) { "Hello" } // ["Hello", "Hello", "Hello"] +``` + +### **2. Accessing List Elements** + +#### **Index-based Access** +```kotlin +val numbers = listOf(10, 20, 30, 40, 50) +val first = numbers[0] // 10 +val third = numbers[2] // 30 +val last = numbers.last() // 50 +``` + +#### **Safe Access Methods** +```kotlin +val numbers = listOf(10, 20, 30, 40, 50) +val element = numbers.getOrNull(10) // null (safe access) +val elementWithDefault = numbers.getOrElse(10) { -1 } // -1 (default value) +``` + +### **3. Modifying Mutable Lists** + +#### **Adding Elements** +```kotlin +val numbers = mutableListOf(1, 2, 3) +numbers.add(4) // Add to end +numbers.add(0, 0) // Add at specific index +numbers.addAll(listOf(5, 6)) // Add multiple elements +``` + +#### **Removing Elements** +```kotlin +val numbers = mutableListOf(1, 2, 3, 4, 5) +numbers.remove(3) // Remove by value +numbers.removeAt(1) // Remove by index +numbers.removeAll { it % 2 == 0 } // Remove all even numbers +``` + +#### **Updating Elements** +```kotlin +val numbers = mutableListOf(1, 2, 3, 4, 5) +numbers[0] = 100 // Direct assignment +numbers.set(1, 200) // Using set() method +``` + +### **4. List Properties** + +```kotlin +val numbers = listOf(1, 2, 3, 4, 5) +println("Size: ${numbers.size}") // 5 +println("Is empty: ${numbers.isEmpty()}") // false +println("Is not empty: ${numbers.isNotEmpty()}") // true +println("First element: ${numbers.first()}") // 1 +println("Last element: ${numbers.last()}") // 5 +``` + +### **5. Iterating Through Lists** + +#### **Using for loop with indices** +```kotlin +val numbers = listOf(10, 20, 30, 40, 50) +for (i in numbers.indices) { + println("Index $i: ${numbers[i]}") +} +``` + +#### **Using for-each loop** +```kotlin +val numbers = listOf(10, 20, 30, 40, 50) +for (number in numbers) { + println("Number: $number") +} +``` + +#### **Using forEach function** +```kotlin +val numbers = listOf(10, 20, 30, 40, 50) +numbers.forEach { number -> + println("Number: $number") +} +``` + +#### **Using forEachIndexed** +```kotlin +val numbers = listOf(10, 20, 30, 40, 50) +numbers.forEachIndexed { index, number -> + println("Index $index: $number") +} +``` + +### **6. List Searching and Filtering** + +#### **Finding Elements** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) +val firstEven = numbers.find { it % 2 == 0 } // 2 +val lastEven = numbers.findLast { it % 2 == 0 } // 10 +val hasEven = numbers.any { it % 2 == 0 } // true +val allEven = numbers.all { it % 2 == 0 } // false +``` + +#### **Filtering Elements** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) +val evenNumbers = numbers.filter { it % 2 == 0 } // [2, 4, 6, 8, 10] +val oddNumbers = numbers.filterNot { it % 2 == 0 } // [1, 3, 5, 7, 9] +val firstThree = numbers.take(3) // [1, 2, 3] +val lastThree = numbers.takeLast(3) // [8, 9, 10] +``` + +### **7. List Transformation** + +#### **Mapping Elements** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5) +val doubled = numbers.map { it * 2 } // [2, 4, 6, 8, 10] +val squared = numbers.map { it * it } // [1, 4, 9, 16, 25] +val withIndex = numbers.mapIndexed { index, value -> "$index: $value" } +``` + +#### **Flattening Lists** +```kotlin +val listOfLists = listOf( + listOf(1, 2, 3), + listOf(4, 5, 6), + listOf(7, 8, 9) +) +val flattened = listOfLists.flatten() // [1, 2, 3, 4, 5, 6, 7, 8, 9] +``` + +## ๐ŸŽฏ Key Concepts Explained + +### **1. Immutable vs Mutable Lists** +```kotlin +// Immutable List - cannot be modified +val immutableList = listOf(1, 2, 3) +// immutableList.add(4) // โŒ Compilation error + +// Mutable List - can be modified +val mutableList = mutableListOf(1, 2, 3) +mutableList.add(4) // โœ… Can modify +``` + +### **2. List vs Array** +```kotlin +// Array - fixed size, mutable +val array = arrayOf(1, 2, 3) +array[0] = 10 // โœ… Can modify + +// List - dynamic size, immutable by default +val list = listOf(1, 2, 3) +// list[0] = 10 // โŒ Compilation error + +// MutableList - dynamic size, mutable +val mutableList = mutableListOf(1, 2, 3) +mutableList[0] = 10 // โœ… Can modify +``` + +### **3. List Performance Characteristics** +- **Access by index**: O(1) - very fast +- **Search by value**: O(n) - linear time +- **Add/Remove at end**: O(1) - very fast +- **Add/Remove at beginning/middle**: O(n) - slower + +## ๐Ÿงช Running the Examples + +### **Step 1: Open the File** +1. Navigate to `src/41_list.kt` +2. Open it in IntelliJ IDEA + +### **Step 2: Run the Program** +1. Right-click on the file +2. Select "Run '41_listKt'" +3. Observe the output + +## ๐ŸŽฎ Hands-On Exercises + +### **Exercise 1: List Manipulation** +Create a mutable list of fruits and perform various operations. + +**Solution:** +```kotlin +fun main() { + val fruits = mutableListOf("Apple", "Banana", "Orange") + println("Original: $fruits") + + fruits.add("Grape") + fruits.add(0, "Strawberry") + fruits.remove("Banana") + + println("Modified: $fruits") + println("Size: ${fruits.size}") +} +``` + +### **Exercise 2: List Filtering and Mapping** +Create a list of numbers and perform filtering and mapping operations. + +**Solution:** +```kotlin +fun main() { + val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + + val evenSquares = numbers + .filter { it % 2 == 0 } + .map { it * it } + + println("Original: $numbers") + println("Even squares: $evenSquares") + println("Sum of even squares: ${evenSquares.sum()}") +} +``` + +### **Exercise 3: List Statistics** +Calculate various statistics for a list of numbers. + +**Solution:** +```kotlin +fun analyzeList(numbers: List) { + val count = numbers.size + val sum = numbers.sum() + val average = sum.toDouble() / count + val min = numbers.minOrNull() ?: 0 + val max = numbers.maxOrNull() ?: 0 + val evenCount = numbers.count { it % 2 == 0 } + val oddCount = numbers.count { it % 2 != 0 } + + println("Count: $count") + println("Sum: $sum") + println("Average: $average") + println("Min: $min, Max: $max") + println("Even: $evenCount, Odd: $oddCount") +} + +fun main() { + val numbers = listOf(23, 45, 12, 67, 34, 89, 56, 78) + analyzeList(numbers) +} +``` + +### **Exercise 4: List Transformation** +Transform a list of strings in various ways. + +**Solution:** +```kotlin +fun main() { + val words = listOf("hello", "world", "kotlin", "programming", "language") + + val capitalized = words.map { it.capitalize() } + val longWords = words.filter { it.length> 5 } + val wordLengths = words.map { it.length } + val totalLength = wordLengths.sum() + + println("Original: $words") + println("Capitalized: $capitalized") + println("Long words: $longWords") + println("Word lengths: $wordLengths") + println("Total length: $totalLength") +} +``` + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Modifying immutable lists**: `listOf(1, 2, 3).add(4)` โŒ + - **Correct**: Use `mutableListOf()` for mutable lists โœ… + +2. **Index out of bounds**: `list[list.size]` โŒ + - **Correct**: Use `list.lastIndex` or check bounds โœ… + +3. **Forgetting list is immutable by default**: Always check if you need `mutableListOf()` โœ… + +4. **Inefficient operations**: `list.removeAt(0)` for large lists โŒ + - **Better**: Use `LinkedList` for frequent insertions/removals โœ… + +## ๐ŸŽฏ What's Next? + +Now that you understand lists, continue with: + +1. **Maps** โ†’ [Maps and HashMaps](03-maps.md) +2. **Sets** โ†’ [Sets and HashSets](04-sets.md) +3. **Functional operations** โ†’ [Filter, Map, and Sorting](05-filter-map-sorting.md) +4. **Advanced collections** โ†’ [Collections Overview](../README.md#collections) + +## ๐Ÿ“š Additional Resources + +- [Official Kotlin Lists Documentation](https://kotlinlang.org/docs/collections-overview.html#list) +- [Kotlin Collections API](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/) +- [List Methods Reference](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/) + +## ๐Ÿ† Summary + +- โœ… You can create both immutable and mutable lists +- โœ… You understand how to add, remove, and modify elements +- โœ… You know list properties and iteration methods +- โœ… You can use functional operations like filter, map, and find +- โœ… You're ready to work with more complex collections! + +**Lists are powerful and flexible collections in Kotlin. Use them wisely! ๐ŸŽ‰** diff --git a/docs/collections/03-maps.md b/docs/collections/03-maps.md new file mode 100644 index 0000000..48e81a7 --- /dev/null +++ b/docs/collections/03-maps.md @@ -0,0 +1,412 @@ +# ๐Ÿ“š Maps and HashMaps in Kotlin + +Maps are key-value pair collections that allow you to store and retrieve data using unique keys. They're essential for creating lookup tables, caches, and organizing related data. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Create and initialize maps in different ways +- โœ… Understand the difference between immutable and mutable maps +- โœ… Add, remove, and modify map entries +- โœ… Use map methods for searching, filtering, and transformation +- โœ… Work with map keys, values, and entries + +## ๐Ÿ” What You'll Learn + +- **Map creation** - Different ways to create maps +- **Key-value pairs** - Understanding map structure +- **Element manipulation** - Adding, removing, and updating entries +- **Map methods** - Built-in functions for map operations +- **Functional operations** - Using lambdas with maps + +## ๐Ÿ“ Prerequisites + +- Understanding of [Lists](02-lists.md) +- Knowledge of [Functions](../functions/01-functions-basics.md) +- Familiarity with [Control Flow](../control-flow/01-if-expressions.md) + +## ๐Ÿ’ป The Code + +Let's examine the maps example: + +**๐Ÿ“ File:** [42_map_hashmap.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/42_map_hashmap.kt) + +## ๐Ÿ” Code Breakdown + +### **1. Map Creation** + +#### **Immutable Maps with `mapOf()`** +```kotlin +val countries = mapOf( + "US" to "United States", + "UK" to "United Kingdom", + "CA" to "Canada" +) + +val scores = mapOf( + "Alice" to 95, + "Bob" to 87, + "Charlie" to 92 +) +``` + +#### **Mutable Maps with `mutableMapOf()`** +```kotlin +val mutableCountries = mutableMapOf( + "US" to "United States", + "UK" to "United Kingdom" +) + +val mutableScores = mutableMapOf() +``` + +#### **Using `HashMap()` Constructor** +```kotlin +val hashMap = HashMap() +hashMap["Alice"] = 95 +hashMap["Bob"] = 87 +``` + +### **2. Accessing Map Elements** + +#### **Using Square Brackets** +```kotlin +val countries = mapOf("US" to "United States", "UK" to "United Kingdom") +val usName = countries["US"] // "United States" +val caName = countries["CA"] // null (key doesn't exist) +``` + +#### **Safe Access Methods** +```kotlin +val countries = mapOf("US" to "United States", "UK" to "United Kingdom") +val usName = countries.get("US") // "United States" +val caName = countries.getOrDefault("CA", "Unknown") // "Unknown" +val frName = countries.getOrElse("FR") { "France" } // "France" +``` + +### **3. Modifying Mutable Maps** + +#### **Adding and Updating Entries** +```kotlin +val scores = mutableMapOf() +scores["Alice"] = 95 // Add new entry +scores["Bob"] = 87 // Add new entry +scores["Alice"] = 98 // Update existing entry +scores.put("Charlie", 92) // Using put() method +``` + +#### **Removing Entries** +```kotlin +val scores = mutableMapOf("Alice" to 95, "Bob" to 87, "Charlie" to 92) +scores.remove("Bob") // Remove by key +scores.remove("Alice", 95) // Remove by key-value pair +scores.clear() // Remove all entries +``` + +### **4. Map Properties** + +```kotlin +val countries = mapOf("US" to "United States", "UK" to "United Kingdom") +println("Size: ${countries.size}") // 2 +println("Is empty: ${countries.isEmpty()}") // false +println("Keys: ${countries.keys}") // [US, UK] +println("Values: ${countries.values}") // [United States, United Kingdom] +``` + +### **5. Iterating Through Maps** + +#### **Using for loop with entries** +```kotlin +val countries = mapOf("US" to "United States", "UK" to "United Kingdom") +for ((code, name) in countries) { + println("$code -> $name") +} +``` + +#### **Using forEach function** +```kotlin +val countries = mapOf("US" to "United States", "UK" to "United Kingdom") +countries.forEach { (code, name) -> + println("$code -> $name") +} +``` + +#### **Iterating over keys and values separately** +```kotlin +val countries = mapOf("US" to "United States", "UK" to "United Kingdom") + +// Iterate over keys +for (code in countries.keys) { + println("Country code: $code") +} + +// Iterate over values +for (name in countries.values) { + println("Country name: $name") +} +``` + +### **6. Map Searching and Filtering** + +#### **Finding Entries** +```kotlin +val scores = mapOf("Alice" to 95, "Bob" to 87, "Charlie" to 92) +val aliceScore = scores["Alice"] // 95 +val hasHighScore = scores.any { it.value>= 90 } // true +val allHighScores = scores.all { it.value>= 80 } // true +``` + +#### **Filtering Entries** +```kotlin +val scores = mapOf("Alice" to 95, "Bob" to 87, "Charlie" to 92, "David" to 78) +val highScores = scores.filter { it.value>= 90 } // {Alice=95, Charlie=92} +val lowScores = scores.filterNot { it.value>= 80 } // {David=78} +val topThree = scores.toList().sortedByDescending { it.second }.take(3).toMap() +``` + +### **7. Map Transformation** + +#### **Transforming Keys and Values** +```kotlin +val scores = mapOf("Alice" to 95, "Bob" to 87, "Charlie" to 92) + +// Transform values +val letterGrades = scores.mapValues { (_, score) -> + when { + score>= 90 -> "A" + score>= 80 -> "B" + score>= 70 -> "C" + else -> "D" + } +} + +// Transform keys +val upperCaseNames = scores.mapKeys { (name, _) -> name.uppercase() } +``` + +#### **Creating Lists from Maps** +```kotlin +val scores = mapOf("Alice" to 95, "Bob" to 87, "Charlie" to 92) + +val names = scores.keys.toList() // [Alice, Bob, Charlie] +val scoreValues = scores.values.toList() // [95, 87, 92] +val entries = scores.toList() // [(Alice, 95), (Bob, 87), (Charlie, 92)] +``` + +## ๐ŸŽฏ Key Concepts Explained + +### **1. Immutable vs Mutable Maps** +```kotlin +// Immutable Map - cannot be modified +val immutableMap = mapOf("A" to 1, "B" to 2) +// immutableMap["C"] = 3 // โŒ Compilation error + +// Mutable Map - can be modified +val mutableMap = mutableMapOf("A" to 1, "B" to 2) +mutableMap["C"] = 3 // โœ… Can modify +``` + +### **2. Map vs List vs Array** +```kotlin +// Array - indexed by position, fixed size +val array = arrayOf("Alice", "Bob", "Charlie") +val name = array[0] // "Alice" + +// List - indexed by position, dynamic size +val list = listOf("Alice", "Bob", "Charlie") +val name = list[0] // "Alice" + +// Map - indexed by key, dynamic size +val map = mapOf("first" to "Alice", "second" to "Bob") +val name = map["first"] // "Alice" +``` + +### **3. Map Performance Characteristics** +- **Access by key**: O(1) - very fast (average case) +- **Search by value**: O(n) - linear time +- **Add/Remove**: O(1) - very fast (average case) +- **Memory usage**: Higher than lists due to key storage + +### **4. Key Requirements** +```kotlin +// Keys must be unique +val scores = mutableMapOf() +scores["Alice"] = 95 +scores["Alice"] = 98 // Overwrites previous value + +// Keys must be immutable (or at least stable) +val badMap = mutableMapOf, String>() // โŒ Don't do this +val goodMap = mutableMapOf() // โœ… Do this +``` + +## ๐Ÿงช Running the Examples + +### **Step 1: Open the File** +1. Navigate to `src/42_map_hashmap.kt` +2. Open it in IntelliJ IDEA + +### **Step 2: Run the Program** +1. Right-click on the file +2. Select "Run '42_map_hashmapKt'" +3. Observe the output + +## ๐ŸŽฎ Hands-On Exercises + +### **Exercise 1: Student Grades** +Create a map to store student grades and perform various operations. + +**Solution:** +```kotlin +fun main() { + val grades = mutableMapOf() + + // Add grades + grades["Alice"] = 95 + grades["Bob"] = 87 + grades["Charlie"] = 92 + grades["David"] = 78 + + println("All grades: $grades") + + // Update a grade + grades["Bob"] = 89 + println("After update: $grades") + + // Remove a student + grades.remove("David") + println("After removal: $grades") + + // Find average grade + val average = grades.values.average() + println("Average grade: $average") +} +``` + +### **Exercise 2: Word Frequency Counter** +Count the frequency of words in a sentence. + +**Solution:** +```kotlin +fun countWords(sentence: String): Map { + val words = sentence.lowercase().split(" ") + val frequency = mutableMapOf() + + for (word in words) { + val cleanWord = word.trim('.', ',', '!', '?') + frequency[cleanWord] = frequency.getOrDefault(cleanWord, 0) + 1 + } + + return frequency +} + +fun main() { + val sentence = "Hello world! Hello Kotlin! Welcome to the world of Kotlin programming." + val wordCount = countWords(sentence) + + println("Word frequencies:") + wordCount.forEach { (word, count) -> + println("$word: $count") + } +} +``` + +### **Exercise 3: Map Filtering and Transformation** +Create a map of products and prices, then filter and transform it. + +**Solution:** +```kotlin +fun main() { + val products = mapOf( + "Laptop" to 999.99, + "Mouse" to 29.99, + "Keyboard" to 79.99, + "Monitor" to 299.99, + "Headphones" to 149.99 + ) + + // Find expensive products (>100ใƒ‰ใƒซ) + val expensive = products.filter { it.value> 100 } + println("Expensive products: $expensive") + + // Apply 20% discount + val discounted = products.mapValues { (_, price) -> price * 0.8 } + println("Discounted prices: $discounted") + + // Find total value + val total = products.values.sum() + println("Total value: $total") +} +``` + +### **Exercise 4: Nested Maps** +Create a nested map structure for organizing data. + +**Solution:** +```kotlin +fun main() { + val students = mapOf( + "Alice" to mapOf( + "age" to 20, + "major" to "Computer Science", + "grades" to mapOf("Math" to 95, "Physics" to 88, "Programming" to 92) + ), + "Bob" to mapOf( + "age" to 22, + "major" to "Mathematics", + "grades" to mapOf("Math" to 98, "Physics" to 85, "Programming" to 78) + ) + ) + + // Access nested data + val aliceAge = students["Alice"]?.get("age") + val bobMathGrade = students["Bob"]?.get("grades")?.get("Math") + + println("Alice's age: $aliceAge") + println("Bob's Math grade: $bobMathGrade") + + // Print all student information + students.forEach { (name, info) -> + println("\n$name:") + info.forEach { (key, value) -> + println(" $key: $value") + } + } +} +``` + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Accessing non-existent keys**: `map["key"]` might return `null` โŒ + - **Better**: Use `getOrDefault()` or `getOrElse()` โœ… + +2. **Modifying immutable maps**: `mapOf("A" to 1)["B"] = 2` โŒ + - **Correct**: Use `mutableMapOf()` for mutable maps โœ… + +3. **Using mutable objects as keys**: Keys should be immutable โœ… + +4. **Forgetting map keys are unique**: Adding same key overwrites value โœ… + +## ๐ŸŽฏ What's Next? + +Now that you understand maps, continue with: + +1. **Sets** โ†’ [Sets and HashSets](04-sets.md) +2. **Functional operations** โ†’ [Filter, Map, and Sorting](05-filter-map-sorting.md) +3. **Advanced collections** โ†’ [Collections Overview](../README.md#collections) +4. **Null safety** โ†’ [Null Safety](../null-safety/01-null-safety.md) + +## ๐Ÿ“š Additional Resources + +- [Official Kotlin Maps Documentation](https://kotlinlang.org/docs/collections-overview.html#map) +- [Kotlin Collections API](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/) +- [Map Methods Reference](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/) + +## ๐Ÿ† Summary + +- โœ… You can create both immutable and mutable maps +- โœ… You understand how to add, remove, and modify entries +- โœ… You know map properties and iteration methods +- โœ… You can use functional operations like filter, map, and transform +- โœ… You're ready to work with sets and other collections! + +**Maps are powerful for organizing data by keys. Use them to create efficient lookups! ๐ŸŽ‰** diff --git a/docs/collections/04-sets.md b/docs/collections/04-sets.md new file mode 100644 index 0000000..b00c462 --- /dev/null +++ b/docs/collections/04-sets.md @@ -0,0 +1,385 @@ +# ๐Ÿ“š Sets and HashSets in Kotlin + +Sets are collections that store unique elements without any specific order. They're perfect for removing duplicates, checking membership, and performing mathematical set operations like union, intersection, and difference. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Create and initialize sets in different ways +- โœ… Understand the difference between immutable and mutable sets +- โœ… Add, remove, and check for elements in sets +- โœ… Use set methods for mathematical operations +- โœ… Work with set properties and iteration + +## ๐Ÿ” What You'll Learn + +- **Set creation** - Different ways to create sets +- **Uniqueness** - How sets ensure no duplicate elements +- **Element manipulation** - Adding, removing, and checking elements +- **Set operations** - Union, intersection, difference, and subset operations +- **Functional operations** - Using lambdas with sets + +## ๐Ÿ“ Prerequisites + +- Understanding of [Maps](03-maps.md) +- Knowledge of [Functions](../functions/01-functions-basics.md) +- Familiarity with [Control Flow](../control-flow/01-if-expressions.md) + +## ๐Ÿ’ป The Code + +Let's examine the sets example: + +**๐Ÿ“ File:** [43_set_hashset.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/43_set_hashset.kt) + +## ๐Ÿ” Code Breakdown + +### **1. Set Creation** + +#### **Immutable Sets with `setOf()`** +```kotlin +val numbers = setOf(1, 2, 3, 4, 5) +val names = setOf("Alice", "Bob", "Charlie") +val empty = setOf() // Empty set with explicit type +``` + +#### **Mutable Sets with `mutableSetOf()`** +```kotlin +val mutableNumbers = mutableSetOf(1, 2, 3, 4, 5) +val mutableNames = mutableSetOf("Alice", "Bob", "Charlie") +``` + +#### **Using `HashSet()` Constructor** +```kotlin +val hashSet = HashSet() +hashSet.add("Alice") +hashSet.add("Bob") +``` + +### **2. Adding and Removing Elements** + +#### **Adding Elements** +```kotlin +val names = mutableSetOf() +names.add("Alice") // Add single element +names.addAll(listOf("Bob", "Charlie")) // Add multiple elements +names += "David" // Using += operator +``` + +#### **Removing Elements** +```kotlin +val names = mutableSetOf("Alice", "Bob", "Charlie", "David") +names.remove("Bob") // Remove by value +names.removeAll { it.startsWith("A") } // Remove all names starting with "A" +names.clear() // Remove all elements +``` + +### **3. Checking Set Membership** + +#### **Basic Membership Tests** +```kotlin +val numbers = setOf(1, 2, 3, 4, 5) +val hasThree = 3 in numbers // true +val hasTen = 10 in numbers // false +val notHasTen = 10 !in numbers // true +``` + +#### **Using Methods** +```kotlin +val numbers = setOf(1, 2, 3, 4, 5) +val containsThree = numbers.contains(3) // true +val containsTen = numbers.contains(10) // false +``` + +### **4. Set Properties** + +```kotlin +val numbers = setOf(1, 2, 3, 4, 5) +println("Size: ${numbers.size}") // 5 +println("Is empty: ${numbers.isEmpty()}") // false +println("Is not empty: ${numbers.isNotEmpty()}") // true +``` + +### **5. Iterating Through Sets** + +#### **Using for loop** +```kotlin +val names = setOf("Alice", "Bob", "Charlie") +for (name in names) { + println("Name: $name") +} +``` + +#### **Using forEach function** +```kotlin +val names = setOf("Alice", "Bob", "Charlie") +names.forEach { name -> + println("Name: $name") +} +``` + +#### **Using forEachIndexed** +```kotlin +val names = setOf("Alice", "Bob", "Charlie") +names.forEachIndexed { index, name -> + println("Index $index: $name") +} +``` + +### **6. Set Mathematical Operations** + +#### **Union (Combining Sets)** +```kotlin +val set1 = setOf(1, 2, 3) +val set2 = setOf(3, 4, 5) +val union = set1.union(set2) // [1, 2, 3, 4, 5] +val unionOperator = set1 + set2 // Same result using + operator +``` + +#### **Intersection (Common Elements)** +```kotlin +val set1 = setOf(1, 2, 3, 4) +val set2 = setOf(3, 4, 5, 6) +val intersection = set1.intersect(set2) // [3, 4] +``` + +#### **Difference (Elements in First Set but Not in Second)** +```kotlin +val set1 = setOf(1, 2, 3, 4) +val set2 = setOf(3, 4, 5, 6) +val difference = set1.subtract(set2) // [1, 2] +``` + +#### **Symmetric Difference (Elements in Either Set but Not Both)** +```kotlin +val set1 = setOf(1, 2, 3, 4) +val set2 = setOf(3, 4, 5, 6) +val symmetricDiff = set1.union(set2).subtract(set1.intersect(set2)) // [1, 2, 5, 6] +``` + +### **7. Set Relationships** + +#### **Subset and Superset** +```kotlin +val set1 = setOf(1, 2, 3) +val set2 = setOf(1, 2, 3, 4, 5) +val isSubset = set1.all { it in set2 } // true +val isSuperset = set2.all { it in set1 } // false +``` + +#### **Disjoint Sets (No Common Elements)** +```kotlin +val set1 = setOf(1, 2, 3) +val set2 = setOf(4, 5, 6) +val areDisjoint = set1.none { it in set2 } // true +``` + +### **8. Set Filtering and Transformation** + +#### **Filtering Elements** +```kotlin +val numbers = setOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) +val evenNumbers = numbers.filter { it % 2 == 0 } // [2, 4, 6, 8, 10] +val oddNumbers = numbers.filterNot { it % 2 == 0 } // [1, 3, 5, 7, 9] +``` + +#### **Transforming Elements** +```kotlin +val numbers = setOf(1, 2, 3, 4, 5) +val doubled = numbers.map { it * 2 } // [2, 4, 6, 8, 10] +val squared = numbers.map { it * it } // [1, 4, 9, 16, 25] +``` + +## ๐ŸŽฏ Key Concepts Explained + +### **1. Uniqueness Guarantee** +```kotlin +val numbers = mutableSetOf(1, 2, 3, 3, 4, 4, 5) +println(numbers) // [1, 2, 3, 4, 5] - duplicates automatically removed +``` + +### **2. Ordering** +```kotlin +// Sets don't guarantee order +val set1 = setOf(3, 1, 4, 1, 5, 9) +val set2 = setOf(9, 5, 1, 4, 3, 1) +println(set1 == set2) // true - order doesn't matter for equality +``` + +### **3. Set vs List vs Array** +```kotlin +// Array - indexed, can have duplicates, fixed size +val array = arrayOf(1, 2, 2, 3) +array[0] = 10 // โœ… Can modify + +// List - indexed, can have duplicates, dynamic size +val list = listOf(1, 2, 2, 3) +// list[0] = 10 // โŒ Compilation error + +// Set - no index, no duplicates, dynamic size +val set = setOf(1, 2, 3) // Note: 2 appears only once +// set[0] = 10 // โŒ No indexing +``` + +### **4. Performance Characteristics** +- **Add/Remove**: O(1) - very fast (average case) +- **Contains check**: O(1) - very fast (average case) +- **Iteration**: O(n) - linear time +- **Memory usage**: Similar to lists + +## ๐Ÿงช Running the Examples + +### **Step 1: Open the File** +1. Navigate to `src/43_set_hashset.kt` +2. Open it in IntelliJ IDEA + +### **Step 2: Run the Program** +1. Right-click on the file +2. Select "Run '43_set_hashsetKt'" +3. Observe the output + +## ๐ŸŽฎ Hands-On Exercises + +### **Exercise 1: Unique Word Counter** +Create a set to count unique words in a sentence. + +**Solution:** +```kotlin +fun main() { + val sentence = "Hello world! Hello Kotlin! Welcome to the world of Kotlin programming." + val words = sentence.lowercase().split(" ") + val uniqueWords = words.toSet() + + println("All words: $words") + println("Unique words: $uniqueWords") + println("Total words: ${words.size}") + println("Unique word count: ${uniqueWords.size}") + println("Duplicate words: ${words.size - uniqueWords.size}") +} +``` + +### **Exercise 2: Set Operations** +Perform various set operations on two sets of numbers. + +**Solution:** +```kotlin +fun main() { + val setA = setOf(1, 2, 3, 4, 5) + val setB = setOf(4, 5, 6, 7, 8) + + println("Set A: $setA") + println("Set B: $setB") + println("Union: ${setA.union(setB)}") + println("Intersection: ${setA.intersect(setB)}") + println("A - B: ${setA.subtract(setB)}") + println("B - A: ${setB.subtract(setA)}") + println("Symmetric difference: ${setA.union(setB).subtract(setA.intersect(setB))}") +} +``` + +### **Exercise 3: Student Course Registration** +Manage student course registrations using sets. + +**Solution:** +```kotlin +fun main() { + val mathStudents = mutableSetOf("Alice", "Bob", "Charlie") + val physicsStudents = mutableSetOf("Bob", "David", "Eve") + val programmingStudents = mutableSetOf("Alice", "Charlie", "Frank") + + println("Math students: $mathStudents") + println("Physics students: $physicsStudents") + println("Programming students: $programmingStudents") + + // Students taking multiple courses + val multiCourseStudents = mathStudents.intersect(physicsStudents) + .union(mathStudents.intersect(programmingStudents)) + .union(physicsStudents.intersect(programmingStudents)) + + println("Students taking multiple courses: $multiCourseStudents") + + // All unique students + val allStudents = mathStudents.union(physicsStudents).union(programmingStudents) + println("All students: $allStudents") + + // Students taking only one course + val singleCourseStudents = allStudents.subtract(multiCourseStudents) + println("Students taking only one course: $singleCourseStudents") +} +``` + +### **Exercise 4: Set Filtering and Analysis** +Create a set of numbers and perform various analyses. + +**Solution:** +```kotlin +fun analyzeNumberSet(numbers: Set) { + val evenNumbers = numbers.filter { it % 2 == 0 } + val oddNumbers = numbers.filter { it % 2 != 0 } + val primeNumbers = numbers.filter { isPrime(it) } + val perfectSquares = numbers.filter { isPerfectSquare(it) } + + println("Original set: $numbers") + println("Even numbers: $evenNumbers") + println("Odd numbers: $oddNumbers") + println("Prime numbers: $primeNumbers") + println("Perfect squares: $perfectSquares") + println("Sum: ${numbers.sum()}") + println("Average: ${numbers.average()}") +} + +fun isPrime(n: Int): Boolean { + if (n < 2) return false + for (i in 2 until n) { + if (n % i == 0) return false + } + return true +} + +fun isPerfectSquare(n: Int): Boolean { + val sqrt = kotlin.math.sqrt(n.toDouble()).toInt() + return sqrt * sqrt == n +} + +fun main() { + val numbers = setOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 25) + analyzeNumberSet(numbers) +} +``` + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Expecting order**: Sets don't maintain insertion order โŒ + - **Correct**: Use `LinkedHashSet` if order matters โœ… + +2. **Using sets for indexed access**: Sets don't support indexing โŒ + - **Correct**: Use lists or arrays for indexed access โœ… + +3. **Forgetting uniqueness**: Adding duplicate elements has no effect โœ… + +4. **Modifying immutable sets**: `setOf(1, 2, 3).add(4)` โŒ + - **Correct**: Use `mutableSetOf()` for mutable sets โœ… + +## ๐ŸŽฏ What's Next? + +Now that you understand sets, continue with: + +1. **Functional operations** โ†’ [Filter, Map, and Sorting](05-filter-map-sorting.md) +2. **Advanced collections** โ†’ [Collections Overview](../README.md#collections) +3. **Null safety** โ†’ [Null Safety](../null-safety/01-null-safety.md) +4. **Functional programming** โ†’ [Functional Programming](../functional-programming/01-lambdas.md) + +## ๐Ÿ“š Additional Resources + +- [Official Kotlin Sets Documentation](https://kotlinlang.org/docs/collections-overview.html#set) +- [Kotlin Collections API](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/) +- [Set Methods Reference](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-set/) + +## ๐Ÿ† Summary + +- โœ… You can create both immutable and mutable sets +- โœ… You understand how sets ensure uniqueness +- โœ… You know how to perform mathematical set operations +- โœ… You can use functional operations like filter and map +- โœ… You're ready to work with advanced collection operations! + +**Sets are perfect for managing unique collections and performing mathematical operations! ๐ŸŽ‰** diff --git a/docs/collections/05-filter-map-sorting.md b/docs/collections/05-filter-map-sorting.md new file mode 100644 index 0000000..578574f --- /dev/null +++ b/docs/collections/05-filter-map-sorting.md @@ -0,0 +1,500 @@ +# ๐Ÿ“š Filter, Map, and Sorting in Kotlin Collections + +Functional operations on collections allow you to transform, filter, and organize data in a clean and readable way. These operations are fundamental to functional programming and make your code more expressive and maintainable. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Use `filter` and `filterNot` to select elements based on conditions +- โœ… Transform collections with `map` and `mapIndexed` +- โœ… Sort collections using various sorting methods +- โœ… Chain multiple operations together for complex transformations +- โœ… Understand the difference between eager and lazy evaluation + +## ๐Ÿ” What You'll Learn + +- **Filtering operations** - Selecting elements based on predicates +- **Mapping operations** - Transforming elements from one form to another +- **Sorting operations** - Organizing elements in various orders +- **Chaining operations** - Combining multiple operations efficiently +- **Performance considerations** - Understanding when to use different approaches + +## ๐Ÿ“ Prerequisites + +- Understanding of [Lists](02-lists.md), [Maps](03-maps.md), and [Sets](04-sets.md) +- Knowledge of [Functions](../functions/01-functions-basics.md) +- Familiarity with [Lambdas](../functional-programming/01-lambdas.md) + +## ๐Ÿ’ป The Code + +Let's examine the functional operations examples: + +**๐Ÿ“ File:** [44_filter_map_sorting.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/44_filter_map_sorting.kt) + +## ๐Ÿ” Code Breakdown + +### **1. Filtering Operations** + +#### **Basic Filtering with `filter()`** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + +// Filter even numbers +val evenNumbers = numbers.filter { it % 2 == 0 } // [2, 4, 6, 8, 10] + +// Filter numbers greater than 5 +val largeNumbers = numbers.filter { it> 5 } // [6, 7, 8, 9, 10] + +// Filter numbers in a range +val rangeNumbers = numbers.filter { it in 3..7 } // [3, 4, 5, 6, 7] +``` + +#### **Filtering with `filterNot()`** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + +// Filter out even numbers (keep odd numbers) +val oddNumbers = numbers.filterNot { it % 2 == 0 } // [1, 3, 5, 7, 9] + +// Filter out numbers less than 5 +val highNumbers = numbers.filterNot { it < 5 } // [5, 6, 7, 8, 9, 10] +``` + +#### **Filtering with Index** +```kotlin +val names = listOf("Alice", "Bob", "Charlie", "David", "Eve") + +// Filter names with even indices +val evenIndexNames = names.filterIndexed { index, _ -> index % 2 == 0 } +// Result: ["Alice", "Charlie", "Eve"] + +// Filter names that start with a letter and have index> 1 +val filteredNames = names.filterIndexed { index, name -> + index> 1 && name.startsWith("C") +} +// Result: ["Charlie"] +``` + +#### **Filtering with Predicates** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + +// Using predefined predicates +val isEven = { n: Int -> n % 2 == 0 } +val isPositive = { n: Int -> n> 0 } +val isInRange = { n: Int -> n in 1..5 } + +val filtered = numbers.filter { isEven(it) && isPositive(it) && isInRange(it) } +// Result: [2, 4] +``` + +### **2. Mapping Operations** + +#### **Basic Mapping with `map()`** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5) + +// Double each number +val doubled = numbers.map { it * 2 } // [2, 4, 6, 8, 10] + +// Square each number +val squared = numbers.map { it * it } // [1, 4, 9, 16, 25] + +// Convert to string +val strings = numbers.map { "Number: $it" } // ["Number: 1", "Number: 2", ...] +``` + +#### **Mapping with Index using `mapIndexed()`** +```kotlin +val names = listOf("Alice", "Bob", "Charlie") + +// Add index to each name +val indexedNames = names.mapIndexed { index, name -> + "${index + 1}. $name" +} +// Result: ["1. Alice", "2. Bob", "3. Charlie"] + +// Create pairs of index and name +val pairs = names.mapIndexed { index, name -> + index to name +} +// Result: [(0, "Alice"), (1, "Bob"), (2, "Charlie")] +``` + +#### **Mapping with Conditions** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + +// Map even numbers to their square, odd numbers to their double +val transformed = numbers.map { n -> + when { + n % 2 == 0 -> n * n // Even: square + else -> n * 2 // Odd: double + } +} +// Result: [2, 4, 6, 16, 10, 36, 14, 64, 18, 100] +``` + +### **3. Sorting Operations** + +#### **Basic Sorting with `sorted()`** +```kotlin +val numbers = listOf(3, 1, 4, 1, 5, 9, 2, 6) + +// Sort in ascending order +val ascending = numbers.sorted() // [1, 1, 2, 3, 4, 5, 6, 9] + +// Sort in descending order +val descending = numbers.sortedDescending() // [9, 6, 5, 4, 3, 2, 1, 1] +``` + +#### **Custom Sorting with `sortedBy()`** +```kotlin +val names = listOf("Alice", "Bob", "Charlie", "David", "Eve") + +// Sort by length +val byLength = names.sortedBy { it.length } // ["Bob", "Eve", "Alice", "David", "Charlie"] + +// Sort by length in descending order +val byLengthDesc = names.sortedByDescending { it.length } // ["Charlie", "David", "Alice", "Bob", "Eve"] + +// Sort by first letter +val byFirstLetter = names.sortedBy { it.first() } // ["Alice", "Bob", "Charlie", "David", "Eve"] +``` + +#### **Sorting with Multiple Criteria** +```kotlin +data class Person(val name: String, val age: Int, val city: String) + +val people = listOf( + Person("Alice", 25, "New York"), + Person("Bob", 30, "Boston"), + Person("Charlie", 25, "New York"), + Person("David", 30, "Chicago") +) + +// Sort by age first, then by name +val sortedPeople = people.sortedWith( + compareBy { it.age }.thenBy { it.name } +) +``` + +### **4. Chaining Operations** + +#### **Filter then Map** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + +// Filter even numbers, then square them +val evenSquares = numbers + .filter { it % 2 == 0 } + .map { it * it } +// Result: [4, 16, 36, 64, 100] +``` + +#### **Map then Filter** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5) + +// Double numbers, then filter those greater than 5 +val doubledAndFiltered = numbers + .map { it * 2 } + .filter { it> 5 } +// Result: [6, 8, 10] +``` + +#### **Complex Chain** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + +val result = numbers + .filter { it % 2 == 0 } // Keep even numbers + .map { it * it } // Square them + .filter { it> 20 } // Keep squares> 20 + .sorted() // Sort in ascending order +// Result: [36, 64, 100] +``` + +### **5. Advanced Operations** + +#### **Flattening with `flatMap()`** +```kotlin +val words = listOf("hello", "world", "kotlin") + +// Split each word into characters and flatten +val characters = words.flatMap { it.toList() } +// Result: ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', 'k', 'o', 't', 'l', 'i', 'n'] + +// Create all possible pairs +val pairs = words.flatMap { word1 -> + words.map { word2 -> "$word1-$word2" } +} +``` + +#### **Grouping with `groupBy()`** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + +// Group by even/odd +val groupedByParity = numbers.groupBy { it % 2 == 0 } +// Result: {false=[1, 3, 5, 7, 9], true=[2, 4, 6, 8, 10]} + +// Group by range +val groupedByRange = numbers.groupBy { + when { + it <= 3 -> "Small" + it <= 7 -> "Medium" + else -> "Large" + } +} +// Result: {Small=[1, 2, 3], Medium=[4, 5, 6, 7], Large=[8, 9, 10]} +``` + +#### **Partitioning with `partition()`** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + +// Partition into even and odd +val (even, odd) = numbers.partition { it % 2 == 0 } +// even: [2, 4, 6, 8, 10], odd: [1, 3, 5, 7, 9] + +// Partition into small and large +val (small, large) = numbers.partition { it <= 5 } +// small: [1, 2, 3, 4, 5], large: [6, 7, 8, 9, 10] +``` + +## ๐ŸŽฏ Key Concepts Explained + +### **1. Eager vs Lazy Evaluation** +```kotlin +val numbers = listOf(1, 2, 3, 4, 5) + +// Eager evaluation - operations are performed immediately +val eagerResult = numbers.filter { it % 2 == 0 }.map { it * it } + +// Lazy evaluation - operations are performed only when needed +val lazyResult = numbers.asSequence() + .filter { it % 2 == 0 } + .map { it * it } + .toList() +``` + +### **2. Performance Considerations** +```kotlin +val largeList = (1..1000000).toList() + +// Less efficient - creates intermediate collections +val result1 = largeList + .filter { it % 2 == 0 } + .map { it * it } + .take(10) + +// More efficient - uses sequences for lazy evaluation +val result2 = largeList.asSequence() + .filter { it % 2 == 0 } + .map { it * it } + .take(10) + .toList() +``` + +### **3. Immutability** +```kotlin +val original = listOf(1, 2, 3, 4, 5) + +// These operations don't modify the original list +val filtered = original.filter { it> 3 } // [4, 5] +val mapped = original.map { it * 2 } // [2, 4, 6, 8, 10] + +println(original) // Still [1, 2, 3, 4, 5] +``` + +## ๐Ÿงช Running the Examples + +### **Step 1: Open the File** +1. Navigate to `src/44_filter_map_sorting.kt` +2. Open it in IntelliJ IDEA + +### **Step 2: Run the Program** +1. Right-click on the file +2. Select "Run '44_filter_map_sortingKt'" +3. Observe the output + +## ๐ŸŽฎ Hands-On Exercises + +### **Exercise 1: Student Grade Analysis** +Create a list of student grades and perform various analyses. + +**Solution:** +```kotlin +data class Student(val name: String, val grade: Int, val subject: String) + +fun main() { + val students = listOf( + Student("Alice", 95, "Math"), + Student("Bob", 87, "Math"), + Student("Charlie", 92, "Math"), + Student("Alice", 88, "Physics"), + Student("Bob", 91, "Physics"), + Student("Charlie", 85, "Physics") + ) + + // Find top students in Math + val topMathStudents = students + .filter { it.subject == "Math" } + .sortedByDescending { it.grade } + .take(2) + .map { "${it.name}: ${it.grade}" } + + println("Top Math students: $topMathStudents") + + // Calculate average grade by subject + val avgBySubject = students + .groupBy { it.subject } + .mapValues { (_, students) -> students.map { it.grade }.average() } + + println("Average by subject: $avgBySubject") +} +``` + +### **Exercise 2: Text Processing Pipeline** +Process text through multiple transformation steps. + +**Solution:** +```kotlin +fun main() { + val text = "Hello World! Welcome to Kotlin Programming. Let's learn together!" + + val processedText = text + .lowercase() // Convert to lowercase + .split(" ") // Split into words + .filter { it.length> 3 } // Keep words longer than 3 characters + .map { it.trim('.', '!', ',') } // Remove punctuation + .filter { it.isNotEmpty() } // Remove empty strings + .distinct() // Remove duplicates + .sorted() // Sort alphabetically + + println("Original: $text") + println("Processed: $processedText") + + // Word frequency analysis + val wordFreq = text + .lowercase() + .split(" ") + .filter { it.isNotEmpty() } + .groupBy { it.trim('.', '!', ',') } + .mapValues { it.value.size } + .toList() + .sortedByDescending { it.second } + + println("Word frequencies: $wordFreq") +} +``` + +### **Exercise 3: Number Sequence Analysis** +Analyze a sequence of numbers using functional operations. + +**Solution:** +```kotlin +fun analyzeNumbers(numbers: List) { + val analysis = numbers + .filter { it> 0 } // Keep positive numbers + .let { positiveNumbers -> + mapOf( + "count" to positiveNumbers.size, + "sum" to positiveNumbers.sum(), + "average" to positiveNumbers.average(), + "even" to positiveNumbers.filter { it % 2 == 0 }, + "odd" to positiveNumbers.filter { it % 2 != 0 }, + "squares" to positiveNumbers.map { it * it }, + "sorted" to positiveNumbers.sorted(), + "reversed" to positiveNumbers.sortedDescending() + ) + } + + analysis.forEach { (key, value) -> + println("$key: $value") + } +} + +fun main() { + val numbers = listOf(-2, 1, 3, -4, 5, 6, -7, 8, 9, -10) + analyzeNumbers(numbers) +} +``` + +### **Exercise 4: Complex Data Transformation** +Transform complex data structures using functional operations. + +**Solution:** +```kotlin +data class Product(val name: String, val price: Double, val category: String, val rating: Double) + +fun main() { + val products = listOf( + Product("Laptop", 999.99, "Electronics", 4.5), + Product("Mouse", 29.99, "Electronics", 4.2), + Product("Book", 19.99, "Books", 4.8), + Product("Chair", 199.99, "Furniture", 4.1), + Product("Table", 299.99, "Furniture", 4.3), + Product("Pen", 2.99, "Office", 4.0) + ) + + // Find expensive electronics with high ratings + val expensiveElectronics = products + .filter { it.category == "Electronics" && it.price> 100 && it.rating>= 4.0 } + .sortedByDescending { it.rating } + .map { "${it.name} ($${it.price}) - Rating: ${it.rating}" } + + println("Expensive electronics: $expensiveElectronics") + + // Group by category and calculate statistics + val categoryStats = products + .groupBy { it.category } + .mapValues { (_, products) -> + mapOf( + "count" to products.size, + "avgPrice" to products.map { it.price }.average(), + "avgRating" to products.map { it.rating }.average(), + "totalValue" to products.map { it.price }.sum() + ) + } + + println("Category statistics: $categoryStats") +} +``` + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Chaining too many operations**: Can reduce readability โŒ + - **Better**: Break into multiple lines or extract functions โœ… + +2. **Forgetting immutability**: Operations don't modify original collections โœ… + +3. **Using sequences unnecessarily**: For small collections, regular operations are fine โœ… + +4. **Inefficient filtering**: Filter before map when possible โœ… + +## ๐ŸŽฏ What's Next? + +Now that you understand functional operations, continue with: + +1. **Advanced collections** โ†’ [Collections Overview](../README.md#collections) +2. **Functional programming** โ†’ [Functional Programming](../functional-programming/01-lambdas.md) +3. **Null safety** โ†’ [Null Safety](../null-safety/01-null-safety.md) +4. **Coroutines** โ†’ [Coroutines](../coroutines/01-introduction.md) + +## ๐Ÿ“š Additional Resources + +- [Official Kotlin Collections Documentation](https://kotlinlang.org/docs/collections-overview.html) +- [Kotlin Collections API](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/) +- [Functional Programming in Kotlin](https://kotlinlang.org/docs/fun-interfaces.html) + +## ๐Ÿ† Summary + +- โœ… You can filter collections using various predicates +- โœ… You can transform collections with map operations +- โœ… You can sort collections in multiple ways +- โœ… You can chain operations for complex transformations +- โœ… You understand performance considerations and best practices + +**Functional operations make your code more readable and maintainable. Use them wisely! ๐ŸŽ‰** diff --git a/docs/conclusion.md b/docs/conclusion.md new file mode 100644 index 0000000..772d346 --- /dev/null +++ b/docs/conclusion.md @@ -0,0 +1,136 @@ +# Conclusion - Next Steps in Your Kotlin Journey + +Congratulations! ๐ŸŽ‰ You've completed the comprehensive Kotlin Programming Tutorial for Beginners. You've learned the fundamentals, explored advanced concepts, and built a solid foundation in Kotlin programming. + +## ๐ŸŽฏ **What You've Accomplished** + +### โœ… **Core Concepts Mastered** +- **Variables, Data Types, and Control Flow** - The building blocks of any program +- **Functions and OOP** - Creating reusable code and organizing your programs +- **Collections and Functional Programming** - Working with data efficiently +- **Null Safety** - Writing robust, crash-free code +- **Coroutines** - Asynchronous programming for modern applications + +### ๐Ÿš€ **Skills Developed** +- Writing clean, readable Kotlin code +- Understanding Kotlin's modern language features +- Applying functional programming concepts +- Building object-oriented applications +- Handling asynchronous operations with coroutines + +## ๐ŸŒŸ **Key Takeaways** + +1. **Kotlin is Modern and Safe** - Built-in null safety, smart casts, and concise syntax +2. **Interoperability** - Seamlessly works with existing Java code +3. **Functional First** - Supports both OOP and functional programming paradigms +4. **Coroutines** - Powerful asynchronous programming without callbacks +5. **Android Development** - Official language for Android app development + +## ๐Ÿ› ๏ธ **Practice Projects to Build** + +### ๐ŸŽฎ **Beginner Level** +1. **Calculator App** - Practice functions and control flow +2. **Todo List** - Work with collections and data structures +3. **Number Guessing Game** - Implement loops and user input + +### ๐Ÿ—๏ธ **Intermediate Level** +1. **Student Management System** - Apply OOP concepts +2. **File Processor** - Work with I/O and error handling +3. **Weather App** - Integrate with APIs and coroutines + +### ๐Ÿš€ **Advanced Level** +1. **Chat Application** - Real-time communication with coroutines +2. **E-commerce Platform** - Full-stack application architecture +3. **Android App** - Mobile development with Kotlin + +## ๐Ÿ“š **Continue Learning** + +### **Official Resources** +- [Kotlin Official Documentation](https://kotlinlang.org/docs/home.html) +- [Kotlin Playground](https://play.kotlinlang.org/) - Try code online +- [Kotlin Blog](https://blog.kotlin.team/) - Latest updates and tips + +### **Advanced Topics to Explore** +- **Kotlin Multiplatform** - Share code between platforms +- **Kotlin DSLs** - Domain-specific languages +- **Kotlin Native** - Compile to native binaries +- **Kotlin for Server-Side** - Backend development +- **Kotlin for Data Science** - Scientific computing + +### **Frameworks and Libraries** +- **Spring Boot** - Enterprise applications +- **Ktor** - Asynchronous web framework +- **Exposed** - Database access library +- **Arrow** - Functional programming library +- **Koin** - Dependency injection + +## ๐ŸŽ“ **Certification and Courses** + +- **JetBrains Academy** - Interactive Kotlin courses +- **Google Codelabs** - Android development with Kotlin +- **Udemy/Coursera** - Comprehensive online courses +- **Local Meetups** - Connect with Kotlin developers + +## ๐Ÿค **Join the Community** + +### **Online Communities** +- [Kotlin Slack](https://kotlinlang.slack.com/) +- [Reddit r/Kotlin](https://reddit.com/r/Kotlin) +- [Stack Overflow](https://stackoverflow.com/questions/tagged/kotlin) +- [Kotlin Forum](https://discuss.kotlinlang.org/) + +### **Open Source Contributions** +- Contribute to Kotlin itself +- Help improve documentation +- Create tutorials for others +- Build useful libraries + +## ๐Ÿ’ก **Best Practices to Remember** + +1. **Write Readable Code** - Use meaningful names and clear structure +2. **Leverage Kotlin Features** - Use data classes, extension functions, and smart casts +3. **Handle Errors Gracefully** - Use null safety and exception handling +4. **Test Your Code** - Write unit tests for your functions +5. **Keep Learning** - Technology evolves, stay updated + +## ๐ŸŽฏ **Your Next 30 Days** + +### **Week 1: Practice Fundamentals** +- Build 2-3 small projects using what you've learned +- Solve coding challenges on platforms like LeetCode or HackerRank + +### **Week 2: Explore Advanced Features** +- Deep dive into coroutines and async programming +- Experiment with functional programming concepts + +### **Week 3: Build Something Real** +- Create a project that solves a real problem +- Use external libraries and APIs + +### **Week 4: Share and Learn** +- Write a blog post about what you've learned +- Contribute to open source projects +- Help other beginners + +## ๐ŸŒŸ **Final Words** + +You've taken an important step in your programming journey. Kotlin is not just a languageโ€”it's a gateway to modern software development. Whether you're building Android apps, web services, or desktop applications, the skills you've learned here will serve you well. + +**Remember**: The best way to learn is by doing. Keep coding, keep experimenting, and don't be afraid to make mistakes. Every error is a learning opportunity. + +## ๐Ÿš€ **Ready to Launch?** + +You now have the knowledge and skills to: +- โœ… Write professional Kotlin code +- โœ… Build real-world applications +- โœ… Contribute to open source projects +- โœ… Pursue advanced Kotlin topics +- โœ… Help others learn Kotlin + +**Go forth and code amazing things!** ๐ŸŽ‰ + +--- + +*"The only way to learn a new programming language is by writing programs in it."* - Dennis Ritchie + +**Happy coding with Kotlin!** ๐Ÿš€โœจ diff --git a/docs/control-flow/01-if-expressions.md b/docs/control-flow/01-if-expressions.md new file mode 100644 index 0000000..3c3f7d3 --- /dev/null +++ b/docs/control-flow/01-if-expressions.md @@ -0,0 +1,408 @@ +# ๐ŸŽฏ If Expressions in Kotlin + +Welcome to the world of decision-making in Kotlin! If expressions allow your programs to make choices and execute different code based on conditions. This is where your programs start to become truly dynamic and intelligent. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Write basic if-else statements +- โœ… Use if expressions to return values +- โœ… Understand the difference between statements and expressions +- โœ… Create nested if conditions +- โœ… Use logical operators in conditions + +## ๐Ÿ” What You'll Learn + +- **Basic if statements** - Simple decision-making +- **If expressions** - Using if to return values +- **If-else chains** - Multiple conditions +- **Nested if statements** - Complex decision trees +- **Logical operators** - Combining conditions + +## ๐Ÿ“ Prerequisites + +- Basic understanding of variables and data types +- Completed [String Interpolation](../basics/05-string-interpolation.md) lesson + +## ๐Ÿ’ป The Code + +Let's examine the if expression example: + +```kotlin +fun main(args: Array) { + val a = 2 + val b = 5 + + var maxValue: Int = if (a> b) { + print("a is greater") + a + } else { + print("b is greater") + b + } + + println(maxValue) +} +``` + +**๐Ÿ“ File:** [10_if_expression.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/10_if_expression.kt) + +## ๐Ÿ” Code Breakdown + +### **Variable Declaration** + +```kotlin +val a = 2 +val b = 5 +``` + +- **Two integers** for comparison +- **`val`** makes them immutable (cannot be changed) + +### **If Expression** + +```kotlin +var maxValue: Int = if (a> b) { + print("a is greater") + a + } else { + print("b is greater") + b + } +``` + +- **`if (a> b)`**: Condition to check if `a` is greater than `b` +- **`{ }`**: Code block for when condition is true +- **`else`**: Code block for when condition is false +- **`a` and `b`**: Values returned by the if expression +- **`maxValue`**: Variable that stores the result + +## ๐ŸŽฏ Key Concepts Explained + +### **1. If Statements vs If Expressions** + +#### **Traditional If Statement (No Return Value)** + +```kotlin +val a = 10 +val b = 5 + +if (a> b) { + println("a is greater") +} else { + println("b is greater") +} +``` + +**Characteristics:** +- Executes code blocks +- No return value +- Used for side effects (printing, calculations) + +#### **If Expression (Returns a Value)** + +```kotlin +val a = 10 +val b = 5 + +val maxValue = if (a> b) a else b +println("Maximum value: $maxValue") +``` + +**Characteristics:** +- Returns a value +- Can be assigned to variables +- More functional programming style + +### **2. Basic If Statement Syntax** + +```kotlin +if (condition) { + // Code to execute when condition is true +} else { + // Code to execute when condition is false +} +``` + +**Components:** +- **`if (condition)`**: Boolean expression that evaluates to true/false +- **`{ }`**: Code blocks containing statements +- **`else`**: Optional alternative execution path + +### **3. If Expression Syntax** + +```kotlin +val result = if (condition) { + // Code block that returns a value + value1 +} else { + // Code block that returns a value + value2 +} +``` + +**Key Points:** +- **Last expression** in each block becomes the return value +- **Same type** must be returned from both branches +- **Can be assigned** directly to variables + +## ๐Ÿงช Hands-On Exercises + +### **Exercise 1: Basic If Statement** +Create a program that checks if a number is positive, negative, or zero: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val number = -5 + + if (number> 0) { + println("$number is positive") + } else if (number < 0) { + println("$number is negative") + } else { + println("$number is zero") + } +} +``` + +### **Exercise 2: If Expression for Grade Calculation** +Use if expressions to calculate a letter grade: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val score = 85 + + val grade = if (score>= 90) { + 'A' + } else if (score>= 80) { + 'B' + } else if (score>= 70) { + 'C' + } else if (score>= 60) { + 'D' + } else { + 'F' + } + + println("Score: $score, Grade: $grade") +} +``` + +### **Exercise 3: Complex If Expression** +Create a program that determines the best discount based on purchase amount and customer type: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val purchaseAmount = 150.0 + val isPremiumCustomer = true + + val discount = if (isPremiumCustomer) { + if (purchaseAmount>= 200) { + purchaseAmount * 0.20 // 20% discount + } else if (purchaseAmount>= 100) { + purchaseAmount * 0.15 // 15% discount + } else { + purchaseAmount * 0.10 // 10% discount + } + } else { + if (purchaseAmount>= 200) { + purchaseAmount * 0.10 // 10% discount + } else if (purchaseAmount>= 100) { + purchaseAmount * 0.05 // 5% discount + } else { + 0.0 // No discount + } + } + + val finalAmount = purchaseAmount - discount + println("Purchase Amount: $${purchaseAmount}") + println("Discount: $${discount}") + println("Final Amount: $${finalAmount}") +} +``` + +### **Exercise 4: Logical Operators in If** +Create a program that checks multiple conditions: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val age = 25 + val hasLicense = true + val hasInsurance = false + + val canDrive = if (age>= 18 && hasLicense) { + if (hasInsurance) { + "Can drive safely with insurance" + } else { + "Can drive but needs insurance" + } + } else if (age < 18) { + "Too young to drive" + } else { + "Needs a driver's license" + } + + println(canDrive) +} +``` + +## ๐Ÿ” Advanced If Expression Concepts + +### **1. Single-Line If Expressions** + +```kotlin +val max = if (a> b) a else b +val status = if (isActive) "Online" else "Offline" +val message = if (age>= 18) "Adult" else "Minor" +``` + +**Use when:** +- Simple conditions +- Single expressions +- Quick assignments + +### **2. Multi-Line If Expressions** + +```kotlin +val result = if (condition) { + val temp = calculateTemp() + val processed = process(temp) + processed +} else { + val default = getDefault() + default +} +``` + +**Use when:** +- Complex calculations +- Multiple steps +- Need intermediate variables + +### **3. Nested If Expressions** + +```kotlin +val category = if (age < 13) { + "Child" +} else if (age < 20) { + if (isStudent) "Teen Student" else "Teen" +} else if (age < 65) { + if (isWorking) "Working Adult" else "Adult" +} else { + "Senior" +} +``` + +## ๐Ÿ” Logical Operators + +### **Comparison Operators** + +| Operator | Description | Example | +|----------|-------------|---------| +| **`==`** | Equal to | `a == b` | +| **`!=`** | Not equal to | `a != b` | +| **`>`** | Greater than | `a> b` | +| **`<`** | Less than | `a < b` | +| **`>=`** | Greater than or equal to | `a>= b` | +| **`<=`** | Less than or equal to | `a <= b` | + +### **Logical Operators** + +| Operator | Description | Example | +|----------|-------------|---------| +| **`&&`** | AND (both must be true) | `a> 0 && b> 0` | +| **`\|\|`** | OR (at least one must be true) | `a> 0 \|\| b> 0` | +| **`!`** | NOT (inverts the condition) | `!(a> 0)` | + +### **Examples** + +```kotlin +val age = 25 +val hasLicense = true +val hasInsurance = false + +// Multiple conditions +val canDrive = age>= 18 && hasLicense +val needsInsurance = canDrive && !hasInsurance +val isEligible = age>= 18 && (hasLicense || hasInsurance) +``` + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Missing else branch in expressions**: + ```kotlin + val result = if (a> b) a // โŒ Missing else branch + val result = if (a> b) a else b // โœ… Correct + ``` + +2. **Using assignment instead of comparison**: + ```kotlin + if (a = 5) { } // โŒ Assignment, not comparison + if (a == 5) { } // โœ… Comparison + ``` + +3. **Forgetting curly braces for multiple statements**: + ```kotlin + if (a> b) println("a is greater"); a // โŒ Only first statement executes + if (a> b) { println("a is greater"); a } // โœ… Both statements execute + ``` + +4. **Inconsistent return types**: + ```kotlin + val result = if (a> b) "Greater" else 42 // โŒ Different types + val result = if (a> b) "Greater" else "Less" // โœ… Same type + ``` + +## ๐ŸŽฏ What's Next? + +Excellent! You've mastered if expressions in Kotlin. Now you're ready to: + +1. **Learn when expressions** โ†’ [When Expressions](02-when-expressions.md) +2. **Understand loops** โ†’ [For Loops](03-for-loops.md) +3. **Work with functions** โ†’ [Functions Basics](../functions/01-functions-basics.md) +4. **Explore collections** โ†’ [Arrays](../collections/01-arrays.md) + +## ๐Ÿ“š Additional Resources + +- [Kotlin Control Flow](https://kotlinlang.org/docs/control-flow.html) +- [If Expressions](https://kotlinlang.org/docs/control-flow.html#if-expression) +- [When Expression](https://kotlinlang.org/docs/control-flow.html#when-expression) + +## ๐Ÿ† Summary + +- โœ… You can write basic if-else statements +- โœ… You can use if expressions to return values +- โœ… You understand the difference between statements and expressions +- โœ… You can create nested if conditions +- โœ… You can use logical operators in conditions +- โœ… You're ready to make your programs intelligent! + +**Keep practicing and happy coding! ๐ŸŽ‰** diff --git a/docs/control-flow/02-when-expressions.md b/docs/control-flow/02-when-expressions.md new file mode 100644 index 0000000..fb0853b --- /dev/null +++ b/docs/control-flow/02-when-expressions.md @@ -0,0 +1,473 @@ +# ๐ŸŽฒ When Expressions in Kotlin + +Welcome to the powerful world of when expressions! When expressions are Kotlin's replacement for switch statements and provide a much more flexible and expressive way to handle multiple conditions. They're perfect for replacing long if-else chains with clean, readable code. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Write basic when expressions +- โœ… Use when expressions to return values +- โœ… Handle multiple conditions elegantly +- โœ… Use when expressions with different data types +- โœ… Understand when expressions vs if-else chains + +## ๐Ÿ” What You'll Learn + +- **Basic when expressions** - Simple multiple condition handling +- **When expressions as values** - Using when to return results +- **Multiple conditions** - Handling various cases elegantly +- **Type matching** - Using when with different data types +- **Best practices** - When and how to use when expressions + +## ๐Ÿ“ Prerequisites + +- Basic understanding of if expressions +- Completed [If Expressions](01-if-expressions.md) lesson + +## ๐Ÿ’ป The Code + +Let's examine the when expression example: + +```kotlin +fun main(args: Array) { + val x = 100 + + val str: String = when (x) { + 1 -> "x is 1" + 2 -> "x is 2" + else -> { + "x value is unknown" + "x is an alien" + } + } + + println(str) +} +``` + +**๐Ÿ“ File:** [11_when_expression.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/11_when_expression.kt) + +## ๐Ÿ” Code Breakdown + +### **Variable Declaration** + +```kotlin +val x = 100 +``` + +- **Single variable** to test against multiple values +- **`val`** makes it immutable + +### **When Expression** + +```kotlin +val str: String = when (x) { + 1 -> "x is 1" + 2 -> "x is 2" + else -> { + "x value is unknown" + "x is an alien" + } +} +``` + +- **`when (x)`**: Tests the value of `x` against different cases +- **`1 -> "x is 1"`**: If `x` equals 1, return "x is 1" +- **`2 -> "x is 2"`**: If `x` equals 2, return "x is 2" +- **`else -> { }`**: Default case when no other conditions match +- **`str`**: Variable that stores the result + +## ๐ŸŽฏ Key Concepts Explained + +### **1. When Expression Syntax** + +```kotlin +val result = when (expression) { + value1 -> result1 + value2 -> result2 + value3 -> result3 + else -> defaultResult +} +``` + +**Components:** +- **`when (expression)`**: The value to test +- **`value -> result`**: Each case with its corresponding result +- **`else ->`**: Default case (optional but recommended) + +### **2. When vs If-Else Chains** + +#### **If-Else Chain (Verbose)** + +```kotlin +val grade = if (score>= 90) { + 'A' +} else if (score>= 80) { + 'B' +} else if (score>= 70) { + 'C' +} else if (score>= 60) { + 'D' +} else { + 'F' +} +``` + +#### **When Expression (Clean)** + +```kotlin +val grade = when { + score>= 90 -> 'A' + score>= 80 -> 'B' + score>= 70 -> 'C' + score>= 60 -> 'D' + else -> 'F' +} +``` + +**Advantages of when:** +- โœ… More readable +- โœ… Less repetitive +- โœ… Better performance +- โœ… Easier to maintain + +### **3. Different Types of When Expressions** + +#### **Value-Based When** + +```kotlin +val day = 3 +val dayName = when (day) { + 1 -> "Monday" + 2 -> "Tuesday" + 3 -> "Wednesday" + 4 -> "Thursday" + 5 -> "Friday" + 6 -> "Saturday" + 7 -> "Sunday" + else -> "Invalid day" +} +``` + +#### **Expression-Based When** + +```kotlin +val score = 85 +val grade = when { + score>= 90 -> 'A' + score>= 80 -> 'B' + score>= 70 -> 'C' + score>= 60 -> 'D' + else -> 'F' +} +``` + +#### **Range-Based When** + +```kotlin +val age = 25 +val category = when (age) { + in 0..12 -> "Child" + in 13..19 -> "Teenager" + in 20..64 -> "Adult" + else -> "Senior" +} +``` + +## ๐Ÿงช Hands-On Exercises + +### **Exercise 1: Basic When Expression** +Create a program that converts numbers to day names: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val dayNumber = 3 + + val dayName = when (dayNumber) { + 1 -> "Monday" + 2 -> "Tuesday" + 3 -> "Wednesday" + 4 -> "Thursday" + 5 -> "Friday" + 6 -> "Saturday" + 7 -> "Sunday" + else -> "Invalid day number" + } + + println("Day $dayNumber is $dayName") +} +``` + +### **Exercise 2: When Expression with Ranges** +Create a program that categorizes ages using ranges: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val age = 17 + + val category = when (age) { + in 0..2 -> "Infant" + in 3..5 -> "Toddler" + in 6..12 -> "Child" + in 13..19 -> "Teenager" + in 20..39 -> "Young Adult" + in 40..59 -> "Middle Aged" + in 60..79 -> "Senior" + else -> "Elderly" + } + + println("Age $age belongs to category: $category") +} +``` + +### **Exercise 3: Complex When Expression** +Create a program that determines shipping cost based on weight and destination: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val weight = 2.5 // in kg + val destination = "International" + + val shippingCost = when { + weight <= 1.0 -> { + when (destination) { + "Local" -> 5.0 + "National" -> 8.0 + "International" -> 15.0 + else -> 0.0 + } + } + weight <= 5.0 -> { + when (destination) { + "Local" -> 10.0 + "National" -> 15.0 + "International" -> 25.0 + else -> 0.0 + } + } + weight <= 10.0 -> { + when (destination) { + "Local" -> 15.0 + "National" -> 25.0 + "International" -> 40.0 + else -> 0.0 + } + } + else -> { + when (destination) { + "Local" -> 20.0 + "National" -> 35.0 + "International" -> 60.0 + else -> 0.0 + } + } + } + + println("Weight: ${weight}kg") + println("Destination: $destination") + println("Shipping Cost: $${shippingCost}") +} +``` + +### **Exercise 4: When Expression with Multiple Values** +Create a program that handles multiple conditions elegantly: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val temperature = 25 + val humidity = 70 + val isRaining = false + + val activity = when { + temperature> 30 && humidity> 80 -> "Stay indoors with AC" + temperature> 25 && !isRaining -> "Go for a walk" + temperature in 15..25 && !isRaining -> "Perfect for outdoor activities" + temperature < 15 -> "Bundle up and stay warm" + isRaining -> "Indoor activities recommended" + else -> "Moderate outdoor activities" + } + + println("Temperature: ${temperature}ยฐC") + println("Humidity: ${humidity}%") + println("Raining: $isRaining") + println("Recommended activity: $activity") +} +``` + +## ๐Ÿ” Advanced When Expression Features + +### **1. Multiple Values in One Case** + +```kotlin +val day = 3 +val dayType = when (day) { + 1, 2, 3, 4, 5 -> "Weekday" + 6, 7 -> "Weekend" + else -> "Invalid day" +} +``` + +### **2. Using When with Custom Objects** + +```kotlin +sealed class Shape +data class Circle(val radius: Double) : Shape() +data class Rectangle(val width: Double, val height: Double) : Shape() +data class Triangle(val base: Double, val height: Double) : Shape() + +fun calculateArea(shape: Shape): Double = when (shape) { + is Circle -> Math.PI * shape.radius * shape.radius + is Rectangle -> shape.width * shape.height + is Triangle -> 0.5 * shape.base * shape.height +} +``` + +### **3. When Expression as Statement** + +```kotlin +val score = 85 +when { + score>= 90 -> println("Excellent!") + score>= 80 -> println("Good job!") + score>= 70 -> println("Not bad!") + else -> println("Keep trying!") +} +``` + +## ๐Ÿ” When Expression Best Practices + +### **โœ… Do's** + +1. **Always include an else branch** (unless exhaustive): + ```kotlin + val result = when (value) { + 1 -> "One" + 2 -> "Two" + else -> "Unknown" // โœ… Safe fallback + } + ``` + +2. **Use ranges for numeric comparisons**: + ```kotlin + val category = when (age) { + in 0..12 -> "Child" // โœ… Clean and readable + in 13..19 -> "Teenager" + else -> "Adult" + } + ``` + +3. **Group related cases together**: + ```kotlin + val season = when (month) { + 12, 1, 2 -> "Winter" // โœ… Logical grouping + 3, 4, 5 -> "Spring" + 6, 7, 8 -> "Summer" + 9, 10, 11 -> "Fall" + else -> "Invalid month" + } + ``` + +### **โŒ Don'ts** + +1. **Don't forget the else branch**: + ```kotlin + val result = when (value) { + 1 -> "One" + 2 -> "Two" + // โŒ Missing else branch + } + ``` + +2. **Don't use when for simple if-else**: + ```kotlin + // โŒ Overkill for simple condition + val result = when (a> b) { + true -> a + false -> b + } + + // โœ… Better approach + val result = if (a> b) a else b + ``` + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Missing else branch**: + ```kotlin + val result = when (x) { + 1 -> "One" + 2 -> "Two" + // โŒ Compile error: missing else branch + } + ``` + +2. **Using wrong syntax**: + ```kotlin + when (x) { + 1: "One" // โŒ Wrong syntax + 1 -> "One" // โœ… Correct syntax + } + ``` + +3. **Forgetting to handle all cases**: + ```kotlin + val result = when (x) { + 1 -> "One" + 2 -> "Two" + // โŒ What if x is 3? + } + ``` + +## ๐ŸŽฏ What's Next? + +Excellent! You've mastered when expressions in Kotlin. Now you're ready to: + +1. **Learn loops** โ†’ [For Loops](03-for-loops.md) +2. **Understand while loops** โ†’ [While Loops](04-while-loops.md) +3. **Work with functions** โ†’ [Functions Basics](../functions/01-functions-basics.md) +4. **Explore collections** โ†’ [Arrays](../collections/01-arrays.md) + +## ๐Ÿ“š Additional Resources + +- [Kotlin When Expression](https://kotlinlang.org/docs/control-flow.html#when-expression) +- [Control Flow](https://kotlinlang.org/docs/control-flow.html) +- [Sealed Classes](https://kotlinlang.org/docs/sealed-classes.html) + +## ๐Ÿ† Summary + +- โœ… You can write basic when expressions +- โœ… You can use when expressions to return values +- โœ… You can handle multiple conditions elegantly +- โœ… You can use when expressions with different data types +- โœ… You understand when expressions vs if-else chains +- โœ… You're ready to write clean, readable conditional code! + +**Keep practicing and happy coding! ๐ŸŽ‰** diff --git a/docs/control-flow/03-for-loops.md b/docs/control-flow/03-for-loops.md new file mode 100644 index 0000000..cf2f603 --- /dev/null +++ b/docs/control-flow/03-for-loops.md @@ -0,0 +1,490 @@ +# ๐Ÿ”„ For Loops in Kotlin + +Welcome to the world of loops! For loops are essential for repeating code and iterating over collections. They're one of the most powerful tools for automating repetitive tasks and processing data efficiently. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Write basic for loops with ranges +- โœ… Iterate over collections and arrays +- โœ… Use different loop directions (forward, backward, step) +- โœ… Understand loop control with break and continue +- โœ… Create efficient and readable loops + +## ๐Ÿ” What You'll Learn + +- **Basic for loops** - Simple iteration with ranges +- **Range-based loops** - Using `..`, `downTo`, and `step` +- **Collection iteration** - Looping through lists, arrays, and maps +- **Loop control** - Using break and continue statements +- **Best practices** - Writing efficient and readable loops + +## ๐Ÿ“ Prerequisites + +- Basic understanding of control flow +- Completed [When Expressions](02-when-expressions.md) lesson + +## ๐Ÿ’ป The Code + +Let's examine the for loop example: + +```kotlin +fun main(args: Array) { + for (i in 1..10) { + if (i % 2 == 0) { + println(i) + } + } + + println() + + for (i in 10 downTo 0) { + if (i % 2 == 0) { + println(i) + } + } +} +``` + +**๐Ÿ“ File:** [12_for_loop.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/12_for_loop.kt) + +## ๐Ÿ” Code Breakdown + +### **First For Loop** + +```kotlin +for (i in 1..10) { + if (i % 2 == 0) { + println(i) + } +} +``` + +- **`for (i in 1..10)`**: Loop from 1 to 10 (inclusive) +- **`i`**: Loop variable that takes each value +- **`1..10`**: Range from 1 to 10 +- **`if (i % 2 == 0)`**: Check if number is even +- **`println(i)`**: Print even numbers only + +### **Second For Loop** + +```kotlin +for (i in 10 downTo 0) { + if (i % 2 == 0) { + println(i) + } +} +``` + +- **`for (i in 10 downTo 0)`**: Loop from 10 down to 0 +- **`downTo`**: Reverse direction +- **Same logic**: Print even numbers in descending order + +## ๐ŸŽฏ Key Concepts Explained + +### **1. Basic For Loop Syntax** + +```kotlin +for (variable in range) { + // Code to execute for each iteration +} +``` + +**Components:** +- **`for`**: Loop keyword +- **`variable`**: Loop variable (can be any name) +- **`in`**: Membership operator +- **`range`**: What to iterate over +- **`{ }`**: Loop body + +### **2. Range Types** + +#### **Inclusive Range (`..`)** + +```kotlin +for (i in 1..5) { + println(i) // Prints: 1, 2, 3, 4, 5 +} +``` + +- **`1..5`**: Includes both 1 and 5 +- **Forward direction**: 1 โ†’ 2 โ†’ 3 โ†’ 4 โ†’ 5 + +#### **Exclusive Range (`until`)** + +```kotlin +for (i in 1 until 5) { + println(i) // Prints: 1, 2, 3, 4 (excludes 5) +} +``` + +- **`1 until 5`**: Excludes the upper bound +- **Useful for**: Array indices, avoiding off-by-one errors + +#### **Reverse Range (`downTo`)** + +```kotlin +for (i in 5 downTo 1) { + println(i) // Prints: 5, 4, 3, 2, 1 +} +``` + +- **`5 downTo 1`**: Counts backward +- **Useful for**: Reverse iteration, countdowns + +#### **Step Range** + +```kotlin +for (i in 0..10 step 2) { + println(i) // Prints: 0, 2, 4, 6, 8, 10 +} + +for (i in 10 downTo 0 step 3) { + println(i) // Prints: 10, 7, 4, 1 +} +``` + +- **`step 2`**: Skip every other number +- **`step 3`**: Skip by 3s + +### **3. Collection Iteration** + +#### **Array/List Iteration** + +```kotlin +val numbers = arrayOf(1, 2, 3, 4, 5) + +// By index +for (i in numbers.indices) { + println("Index $i: ${numbers[i]}") +} + +// By value +for (number in numbers) { + println("Number: $number") +} + +// By index and value +for ((index, value) in numbers.withIndex()) { + println("Index $index: $value") +} +``` + +#### **String Iteration** + +```kotlin +val text = "Hello" + +// By character +for (char in text) { + println("Character: $char") +} + +// By index +for (i in text.indices) { + println("Index $i: ${text[i]}") +} +``` + +#### **Map Iteration** + +```kotlin +val map = mapOf("a" to 1, "b" to 2, "c" to 3) + +// By key-value pairs +for ((key, value) in map) { + println("$key -> $value") +} + +// By keys only +for (key in map.keys) { + println("Key: $key") +} + +// By values only +for (value in map.values) { + println("Value: $value") +} +``` + +## ๐Ÿงช Hands-On Exercises + +### **Exercise 1: Basic Range Loops** +Create a program that demonstrates different range types: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + println("Forward range (1..5):") + for (i in 1..5) { + print("$i ") + } + + println("\n\nExclusive range (1 until 5):") + for (i in 1 until 5) { + print("$i ") + } + + println("\n\nReverse range (5 downTo 1):") + for (i in 5 downTo 1) { + print("$i ") + } + + println("\n\nStep range (0..10 step 2):") + for (i in 0..10 step 2) { + print("$i ") + } +} +``` + +### **Exercise 2: Number Pattern Loops** +Create a program that prints different number patterns: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + println("Multiplication table for 5:") + for (i in 1..10) { + println("5 ร—ใฐใค $i = ${5 * i}") + } + + println("\nEven numbers from 2 to 20:") + for (i in 2..20 step 2) { + print("$i ") + } + + println("\n\nCountdown from 10:") + for (i in 10 downTo 1) { + print("$i ") + if (i == 1) println("Blast off!") else print(", ") + } +} +``` + +### **Exercise 3: Collection Iteration** +Create a program that demonstrates different ways to iterate over collections: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val fruits = listOf("Apple", "Banana", "Orange", "Grape", "Mango") + + println("Fruits by index:") + for (i in fruits.indices) { + println("${i + 1}. ${fruits[i]}") + } + + println("\nFruits by value:") + for (fruit in fruits) { + println("โ€ข $fruit") + } + + println("\nFruits with index:") + for ((index, fruit) in fruits.withIndex()) { + println("${index + 1}. $fruit") + } + + println("\nFruits in reverse:") + for (i in fruits.indices.reversed()) { + println("${i + 1}. ${fruits[i]}") + } +} +``` + +### **Exercise 4: Advanced Loop Patterns** +Create a program that demonstrates complex loop patterns: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + println("Pyramid pattern:") + for (i in 1..5) { + // Print spaces + for (j in 1..(5 - i)) { + print(" ") + } + // Print stars + for (j in 1..(2 * i - 1)) { + print("*") + } + println() + } + + println("\nNumber triangle:") + for (i in 1..5) { + for (j in 1..i) { + print("$j ") + } + println() + } + + println("\nAlternating pattern:") + for (i in 1..10) { + val symbol = if (i % 2 == 0) "โ˜…" else "โ˜†" + print("$symbol ") + } +} +``` + +## ๐Ÿ” Advanced For Loop Features + +### **1. Nested Loops** + +```kotlin +// Multiplication table +for (i in 1..5) { + for (j in 1..5) { + print("${i * j}\t") + } + println() +} +``` + +### **2. Loop with Conditions** + +```kotlin +for (i in 1..20) { + when { + i % 3 == 0 && i % 5 == 0 -> println("FizzBuzz") + i % 3 == 0 -> println("Fizz") + i % 5 == 0 -> println("Buzz") + else -> println(i) + } +} +``` + +### **3. Custom Range Functions** + +```kotlin +// Custom step function +fun Int.toward(to: Int): IntProgression { + val step = if (this> to) -1 else 1 + return IntProgression.fromClosedRange(this, to, step) +} + +// Usage +for (i in 5.toward(1)) { + println(i) // Prints: 5, 4, 3, 2, 1 +} +``` + +## ๐Ÿ” Loop Control Statements + +### **1. Break Statement** + +```kotlin +for (i in 1..10) { + if (i == 5) { + break // Exit loop when i equals 5 + } + println(i) +} +// Output: 1, 2, 3, 4 +``` + +### **2. Continue Statement** + +```kotlin +for (i in 1..10) { + if (i % 2 == 0) { + continue // Skip even numbers + } + println(i) +} +// Output: 1, 3, 5, 7, 9 +``` + +### **3. Labeled Loops** + +```kotlin +outer@ for (i in 1..3) { + for (j in 1..3) { + if (i == 2 && j == 2) { + break@outer // Break outer loop + } + println("i=$i, j=$j") + } +} +``` + +## ๐Ÿšจ Common Mistakes to Avoid + +1. **Off-by-one errors**: + ```kotlin + val array = arrayOf(1, 2, 3, 4, 5) + for (i in 0..array.size) { // โŒ Should be array.size - 1 + println(array[i]) + } + + for (i in 0 until array.size) { // โœ… Correct + println(array[i]) + } + ``` + +2. **Infinite loops**: + ```kotlin + for (i in 1..10) { + i++ // โŒ Cannot modify loop variable + } + ``` + +3. **Wrong range direction**: + ```kotlin + for (i in 10..1) { // โŒ Empty range (10 is not <= 1) + println(i) + } + + for (i in 10 downTo 1) { // โœ… Correct + println(i) + } + ``` + +## ๐ŸŽฏ What's Next? + +Excellent! You've mastered for loops in Kotlin. Now you're ready to: + +1. **Learn while loops** โ†’ [While Loops](04-while-loops.md) +2. **Understand break and continue** โ†’ [Break and Continue](05-break-continue.md) +3. **Work with functions** โ†’ [Functions Basics](../functions/01-functions-basics.md) +4. **Explore collections** โ†’ [Arrays](../collections/01-arrays.md) + +## ๐Ÿ“š Additional Resources + +- [Kotlin For Loops](https://kotlinlang.org/docs/control-flow.html#for-loops) +- [Ranges](https://kotlinlang.org/docs/ranges.html) +- [Collections](https://kotlinlang.org/docs/collections-overview.html) + +## ๐Ÿ† Summary + +- โœ… You can write basic for loops with ranges +- โœ… You can iterate over collections and arrays +- โœ… You can use different loop directions (forward, backward, step) +- โœ… You understand loop control with break and continue +- โœ… You can create efficient and readable loops +- โœ… You're ready to automate repetitive tasks! + +**Keep practicing and happy coding! ๐ŸŽ‰** diff --git a/docs/control-flow/04-while-loops.md b/docs/control-flow/04-while-loops.md new file mode 100644 index 0000000..877b3da --- /dev/null +++ b/docs/control-flow/04-while-loops.md @@ -0,0 +1,530 @@ +# ๐Ÿ” While Loops in Kotlin + +Welcome to the world of while loops! While loops are perfect for situations where you don't know in advance how many times you need to repeat a block of code. They continue executing as long as a condition remains true, making them ideal for user input validation, data processing, and game loops. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Write basic while loops +- โœ… Use do-while loops effectively +- โœ… Understand when to use while vs for loops +- โœ… Control loop execution with break and continue +- โœ… Avoid infinite loops and common pitfalls + +## ๐Ÿ” What You'll Learn + +- **Basic while loops** - Simple conditional repetition +- **Do-while loops** - Execute first, then check condition +- **Loop control** - Using break and continue statements +- **Infinite loop prevention** - Best practices and safety +- **Real-world applications** - Practical use cases + +## ๐Ÿ“ Prerequisites + +- Basic understanding of for loops +- Completed [For Loops](03-for-loops.md) lesson + +## ๐Ÿ’ป The Code + +Let's examine the while loop example: + +```kotlin +fun main(args: Array) { + var i = 1 + + while (i <= 5) { + println("Count: $i") + i++ + } + + println("Loop finished!") +} +``` + +**๐Ÿ“ File:** [13_while_loop.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/13_while_loop.kt) + +## ๐Ÿ” Code Breakdown + +### **Variable Initialization** + +```kotlin +var i = 1 +``` + +- **`var i = 1`**: Initialize loop counter +- **`var`** makes it mutable (can be changed) + +### **While Loop** + +```kotlin +while (i <= 5) { + println("Count: $i") + i++ +} +``` + +- **`while (i <= 5)`**: Condition to check before each iteration +- **`{ }`**: Loop body containing statements +- **`println("Count: $i")`**: Print current count +- **`i++`**: Increment counter (crucial to avoid infinite loop) + +## ๐ŸŽฏ Key Concepts Explained + +### **1. While Loop Syntax** + +```kotlin +while (condition) { + // Code to execute while condition is true +} +``` + +**Components:** +- **`while`**: Loop keyword +- **`(condition)`**: Boolean expression that controls the loop +- **`{ }`**: Loop body containing statements + +**Execution Flow:** +1. **Check condition** - Is it true? +2. **If true** - Execute loop body +3. **Repeat** - Go back to step 1 +4. **If false** - Exit loop + +### **2. Do-While Loop Syntax** + +```kotlin +do { + // Code to execute at least once +} while (condition) +``` + +**Key Difference:** +- **While loop**: Check condition first, then execute +- **Do-while loop**: Execute first, then check condition +- **Guarantee**: Do-while always executes at least once + +### **3. When to Use Each Loop Type** + +#### **Use While Loop When:** +- You don't know the number of iterations in advance +- Condition depends on user input +- Processing data until a condition is met +- Game loops or event-driven programming + +#### **Use For Loop When:** +- You know the exact number of iterations +- Iterating over collections or ranges +- Simple counting scenarios + +#### **Use Do-While Loop When:** +- You need to execute code at least once +- Menu-driven programs +- Input validation scenarios + +## ๐Ÿงช Hands-On Exercises + +### **Exercise 1: Basic While Loop** +Create a program that counts down from 10 to 1: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + var count = 10 + + while (count>= 1) { + println("Countdown: $count") + count-- + } + + println("Blast off!") +} +``` + +### **Exercise 2: User Input Validation** +Create a program that asks for a positive number using while loop: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + var input: Int + var attempts = 0 + + do { + print("Enter a positive number: ") + input = readLine()?.toIntOrNull() ?: 0 + attempts++ + + if (input <= 0) { + println("Invalid input. Please try again.") + } + } while (input <= 0) + + println("Valid input received: $input") + println("Number of attempts: $attempts") +} +``` + +### **Exercise 3: Data Processing Loop** +Create a program that processes numbers until a sentinel value is encountered: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + var sum = 0 + var count = 0 + var number: Int + + println("Enter numbers (enter -1 to stop):") + + while (true) { + print("Enter number: ") + number = readLine()?.toIntOrNull() ?: 0 + + if (number == -1) { + break // Exit loop when sentinel value is entered + } + + sum += number + count++ + } + + if (count> 0) { + val average = sum.toDouble() / count + println("Sum: $sum") + println("Count: $count") + println("Average: $average") + } else { + println("No numbers entered.") + } +} +``` + +### **Exercise 4: Menu-Driven Program** +Create a simple calculator using do-while loop: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + var choice: Int + var continueProgram = true + + do { + println("\n=== Simple Calculator ===") + println("1. Addition") + println("2. Subtraction") + println("3. Multiplication") + println("4. Division") + println("5. Exit") + print("Enter your choice (1-5): ") + + choice = readLine()?.toIntOrNull() ?: 0 + + when (choice) { + 1 -> { + print("Enter first number: ") + val a = readLine()?.toDoubleOrNull() ?: 0.0 + print("Enter second number: ") + val b = readLine()?.toDoubleOrNull() ?: 0.0 + println("Result: ${a + b}") + } + 2 -> { + print("Enter first number: ") + val a = readLine()?.toDoubleOrNull() ?: 0.0 + print("Enter second number: ") + val b = readLine()?.toDoubleOrNull() ?: 0.0 + println("Result: ${a - b}") + } + 3 -> { + print("Enter first number: ") + val a = readLine()?.toDoubleOrNull() ?: 0.0 + print("Enter second number: ") + val b = readLine()?.toDoubleOrNull() ?: 0.0 + println("Result: ${a * b}") + } + 4 -> { + print("Enter first number: ") + val a = readLine()?.toDoubleOrNull() ?: 0.0 + print("Enter second number: ") + val b = readLine()?.toDoubleOrNull() ?: 0.0 + if (b != 0.0) { + println("Result: ${a / b}") + } else { + println("Error: Division by zero!") + } + } + 5 -> { + println("Goodbye!") + continueProgram = false + } + else -> println("Invalid choice. Please try again.") + } + } while (continueProgram) +} +``` + +## ๐Ÿ” Advanced While Loop Concepts + +### **1. Nested While Loops** + +```kotlin +var i = 1 +while (i <= 3) { + var j = 1 + while (j <= i) { + print("*") + j++ + } + println() + i++ +} +// Output: +// * +// ** +// *** +``` + +### **2. While Loop with Collections** + +```kotlin +val numbers = mutableListOf(1, 2, 3, 4, 5) +var index = 0 + +while (index < numbers.size) { + if (numbers[index] % 2 == 0) { + numbers[index] *= 2 // Double even numbers + } + index++ +} + +println(numbers) // [1, 4, 3, 8, 5] +``` + +### **3. While Loop with Custom Conditions** + +```kotlin +var password = "" +var attempts = 0 +val correctPassword = "secret123" + +while (password != correctPassword && attempts < 3) { + print("Enter password (attempt ${attempts + 1}/3): ") + password = readLine() ?: "" + attempts++ + + if (password != correctPassword) { + println("Incorrect password. Try again.") + } +} + +if (password == correctPassword) { + println("Access granted!") +} else { + println("Access denied. Too many attempts.") +} +``` + +## ๐Ÿ” Loop Control in While Loops + +### **1. Break Statement** + +```kotlin +var i = 1 +while (true) { + if (i> 10) { + break // Exit loop when i exceeds 10 + } + println(i) + i++ +} +``` + +### **2. Continue Statement** + +```kotlin +var i = 1 +while (i <= 10) { + if (i % 2 == 0) { + i++ + continue // Skip even numbers + } + println("Odd number: $i") + i++ +} +``` + +### **3. Labeled Loops** + +```kotlin +outer@ while (true) { + var i = 1 + while (i <= 5) { + if (i == 3) { + break@outer // Break outer loop + } + println("i = $i") + i++ + } +} +``` + +## ๐Ÿšจ Common Mistakes to Avoid + +### **1. Infinite Loops** + +```kotlin +// โŒ Infinite loop - missing increment +var i = 1 +while (i <= 5) { + println(i) + // i++ is missing! +} + +// โœ… Correct - with increment +var i = 1 +while (i <= 5) { + println(i) + i++ +} +``` + +### **2. Off-by-One Errors** + +```kotlin +// โŒ Wrong condition - will miss last element +var i = 0 +while (i < array.size - 1) { + println(array[i]) + i++ +} + +// โœ… Correct condition +var i = 0 +while (i < array.size) { + println(array[i]) + i++ +} +``` + +### **3. Using Wrong Loop Type** + +```kotlin +// โŒ While loop for simple counting +var i = 1 +while (i <= 10) { + println(i) + i++ +} + +// โœ… For loop is better for counting +for (i in 1..10) { + println(i) +} +``` + +## ๐Ÿ” Best Practices + +### **โœ… Do's** + +1. **Always ensure loop termination**: + ```kotlin + var i = 1 + while (i <= 10) { // โœ… Clear termination condition + println(i) + i++ + } + ``` + +2. **Use meaningful variable names**: + ```kotlin + var count = 0 + while (count < maxAttempts) { // โœ… Clear and descriptive + // Loop body + count++ + } + ``` + +3. **Initialize variables before the loop**: + ```kotlin + var sum = 0 // โœ… Initialize before loop + var i = 1 + while (i <= 10) { + sum += i + i++ + } + ``` + +### **โŒ Don'ts** + +1. **Don't forget to update loop variables**: + ```kotlin + var i = 1 + while (i <= 5) { + println(i) + // โŒ Missing i++ - infinite loop! + } + ``` + +2. **Don't use while loops for simple counting**: + ```kotlin + // โŒ Overkill for simple iteration + var i = 0 + while (i < 10) { + println(i) + i++ + } + + // โœ… Use for loop instead + for (i in 0 until 10) { + println(i) + } + ``` + +## ๐ŸŽฏ What's Next? + +Excellent! You've mastered while loops in Kotlin. Now you're ready to: + +1. **Learn break and continue** โ†’ [Break and Continue](05-break-continue.md) +2. **Work with functions** โ†’ [Functions Basics](../functions/01-functions-basics.md) +3. **Explore collections** โ†’ [Arrays](../collections/01-arrays.md) +4. **Understand OOP** โ†’ [Classes and Constructors](../oop/01-classes-constructors.md) + +## ๐Ÿ“š Additional Resources + +- [Kotlin While Loops](https://kotlinlang.org/docs/control-flow.html#while-loops) +- [Control Flow](https://kotlinlang.org/docs/control-flow.html) +- [Loop Control](https://kotlinlang.org/docs/returns.html) + +## ๐Ÿ† Summary + +- โœ… You can write basic while loops +- โœ… You can use do-while loops effectively +- โœ… You understand when to use while vs for loops +- โœ… You can control loop execution with break and continue +- โœ… You know how to avoid infinite loops and common pitfalls +- โœ… You're ready to handle dynamic repetition scenarios! + +**Keep practicing and happy coding! ๐ŸŽ‰** + diff --git a/docs/control-flow/05-break-continue.md b/docs/control-flow/05-break-continue.md new file mode 100644 index 0000000..639560e --- /dev/null +++ b/docs/control-flow/05-break-continue.md @@ -0,0 +1,582 @@ +# โน๏ธ Break and Continue in Kotlin + +Welcome to the world of loop control! Break and continue statements give you fine-grained control over how your loops execute. They allow you to skip iterations, exit loops early, and create more efficient and readable code. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Use break statements to exit loops early +- โœ… Use continue statements to skip iterations +- โœ… Understand labeled break and continue +- โœ… Choose the right control statement for your needs +- โœ… Write more efficient and readable loops + +## ๐Ÿ” What You'll Learn + +- **Break statements** - Exiting loops prematurely +- **Continue statements** - Skipping specific iterations +- **Labeled statements** - Controlling nested loops +- **Best practices** - When and how to use each statement +- **Real-world applications** - Practical use cases + +## ๐Ÿ“ Prerequisites + +- Basic understanding of loops (for, while) +- Completed [While Loops](04-while-loops.md) lesson + +## ๐Ÿ’ป The Code + +Let's examine the break and continue examples: + +```kotlin +fun main(args: Array) { + for (i in 1..10) { + if (i == 5) { + break // Exit loop when i equals 5 + } + println(i) + } + + println("Loop finished!") +} +``` + +**๐Ÿ“ File:** [15_break_keyword.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/15_break_keyword.kt) + +## ๐Ÿ” Code Breakdown + +### **Break Statement Example** + +```kotlin +for (i in 1..10) { + if (i == 5) { + break // Exit loop when i equals 5 + } + println(i) +} +``` + +- **`for (i in 1..10)`**: Loop from 1 to 10 +- **`if (i == 5)`**: Condition to check +- **`break`**: Exit the loop immediately +- **Output**: Only prints 1, 2, 3, 4 (loop exits at 5) + +## ๐ŸŽฏ Key Concepts Explained + +### **1. Break Statement** + +#### **Basic Break Syntax** + +```kotlin +for (i in 1..10) { + if (condition) { + break // Exit the loop immediately + } + // This code won't execute after break +} +``` + +**What Break Does:** +- **Immediately exits** the innermost loop +- **Skips remaining iterations** +- **Continues execution** after the loop +- **Useful for**: Early termination, error conditions, found items + +#### **Break in Different Loop Types** + +```kotlin +// For loop +for (i in 1..10) { + if (i == 5) break + println(i) +} + +// While loop +var i = 1 +while (i <= 10) { + if (i == 5) break + println(i) + i++ +} + +// Do-while loop +var j = 1 +do { + if (j == 5) break + println(j) + j++ +} while (j <= 10) +``` + +### **2. Continue Statement** + +#### **Basic Continue Syntax** + +```kotlin +for (i in 1..10) { + if (condition) { + continue // Skip to next iteration + } + // This code executes for non-skipped iterations +} +``` + +**What Continue Does:** +- **Skips current iteration** +- **Continues with next iteration** +- **Loop body continues** after continue +- **Useful for**: Skipping invalid data, filtering, conditional processing + +#### **Continue Examples** + +```kotlin +// Skip even numbers +for (i in 1..10) { + if (i % 2 == 0) { + continue // Skip even numbers + } + println("Odd: $i") +} + +// Skip specific values +for (i in 1..10) { + if (i == 3 || i == 7) { + continue // Skip 3 and 7 + } + println(i) +} +``` + +### **3. Labeled Break and Continue** + +#### **Labeled Break** + +```kotlin +outer@ for (i in 1..3) { + for (j in 1..3) { + if (i == 2 && j == 2) { + break@outer // Break outer loop + } + println("i=$i, j=$j") + } +} +``` + +**Output:** +``` +i=1, j=1 +i=1, j=2 +i=1, j=3 +i=2, j=1 +``` + +#### **Labeled Continue** + +```kotlin +outer@ for (i in 1..3) { + for (j in 1..3) { + if (i == 2 && j == 2) { + continue@outer // Continue outer loop + } + println("i=$i, j=$j") + } +} +``` + +**Output:** +``` +i=1, j=1 +i=1, j=2 +i=1, j=3 +i=2, j=1 +i=3, j=1 +i=3, j=2 +i=3, j=3 +``` + +## ๐Ÿงช Hands-On Exercises + +### **Exercise 1: Basic Break Statement** +Create a program that finds the first number divisible by both 3 and 5: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + for (i in 1..100) { + if (i % 3 == 0 && i % 5 == 0) { + println("First number divisible by both 3 and 5: $i") + break // Exit loop after finding first match + } + } +} +``` + +### **Exercise 2: Continue Statement** +Create a program that prints all numbers from 1 to 20, except multiples of 3: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + for (i in 1..20) { + if (i % 3 == 0) { + continue // Skip multiples of 3 + } + print("$i ") + } + println() +} +``` + +### **Exercise 3: Labeled Break** +Create a program that demonstrates labeled break with nested loops: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val targetSum = 15 + + outer@ for (i in 1..5) { + for (j in 1..5) { + for (k in 1..5) { + val sum = i + j + k + if (sum == targetSum) { + println("Found combination: $i + $j + $k = $targetSum") + break@outer // Exit all loops + } + } + } + } +} +``` + +### **Exercise 4: Complex Loop Control** +Create a program that processes a list of numbers with multiple control statements: + +```kotlin +fun main(args: Array) { + // TODO: Add your solution here +} +``` + +**Solution:** +```kotlin +fun main(args: Array) { + val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + var sum = 0 + var count = 0 + + for (number in numbers) { + // Skip negative numbers (though our list doesn't have any) + if (number < 0) { + continue + } + + // Stop if we've processed 5 numbers + if (count>= 5) { + break + } + + // Skip even numbers + if (number % 2 == 0) { + continue + } + + sum += number + count++ + println("Added $number, sum is now $sum") + } + + println("Final sum: $sum") + println("Numbers processed: $count") +} +``` + +## ๐Ÿ” Advanced Control Flow Patterns + +### **1. Break with When Expression** + +```kotlin +for (i in 1..10) { + val action = when { + i < 5 -> "Continue" + i == 5 -> "Break" + else -> "Process" + } + + when (action) { + "Continue" -> continue + "Break" -> break + "Process" -> println("Processing $i") + } +} +``` + +### **2. Continue with Complex Conditions** + +```kotlin +for (i in 1..20) { + // Skip numbers that are multiples of 2, 3, or 5 + if (i % 2 == 0 || i % 3 == 0 || i % 5 == 0) { + continue + } + + // Only process prime numbers (simplified) + if (i> 1) { + println("Prime number: $i") + } +} +``` + +### **3. Break in Data Processing** + +```kotlin +val data = listOf(1, 2, 3, -1, 4, 5) // -1 is sentinel value +var sum = 0 + +for (item in data) { + if (item == -1) { + break // Stop processing at sentinel value + } + sum += item +} + +println("Sum before sentinel: $sum") +``` + +## ๐Ÿ” When to Use Each Statement + +### **โœ… Use Break When:** + +1. **Searching for items**: + ```kotlin + for (item in list) { + if (item == target) { + println("Found: $item") + break // Exit after finding + } + } + ``` + +2. **Error conditions**: + ```kotlin + for (i in 1..10) { + if (i == 0) { + println("Error: Division by zero") + break // Exit on error + } + println(100 / i) + } + ``` + +3. **Performance optimization**: + ```kotlin + for (i in 1..1000) { + if (i * i> 100) { + break // Exit when condition met + } + println("$i squared is ${i * i}") + } + ``` + +### **โœ… Use Continue When:** + +1. **Filtering data**: + ```kotlin + for (number in numbers) { + if (number < 0) { + continue // Skip negative numbers + } + processPositiveNumber(number) + } + ``` + +2. **Skipping invalid input**: + ```kotlin + for (input in inputs) { + if (!isValid(input)) { + continue // Skip invalid input + } + processValidInput(input) + } + ``` + +3. **Conditional processing**: + ```kotlin + for (i in 1..10) { + if (i % 2 == 0) { + continue // Skip even numbers + } + processOddNumber(i) + } + ``` + +## ๐Ÿšจ Common Mistakes to Avoid + +### **1. Infinite Loops with Continue** + +```kotlin +// โŒ Infinite loop - i never increments +var i = 1 +while (i <= 10) { + if (i % 2 == 0) { + continue // Skips the rest of the loop body + } + println(i) + i++ // This line is never reached for even numbers! +} + +// โœ… Correct - increment before continue +var i = 1 +while (i <= 10) { + if (i % 2 == 0) { + i++ // Increment first + continue + } + println(i) + i++ +} +``` + +### **2. Unreachable Code After Break** + +```kotlin +// โŒ Unreachable code +for (i in 1..10) { + if (i == 5) { + break + println("This will never execute") // Unreachable + } + println(i) +} + +// โœ… Correct - no unreachable code +for (i in 1..10) { + if (i == 5) { + break + } + println(i) +} +``` + +### **3. Wrong Label Usage** + +```kotlin +// โŒ Label doesn't exist +for (i in 1..3) { + for (j in 1..3) { + if (i == 2) { + break@nonexistent // Compile error + } + } +} + +// โœ… Correct label usage +outer@ for (i in 1..3) { + for (j in 1..3) { + if (i == 2) { + break@outer // Valid label + } + } +} +``` + +## ๐Ÿ” Best Practices + +### **โœ… Do's** + +1. **Use descriptive labels**: + ```kotlin + searchLoop@ for (i in 1..100) { + if (found) break@searchLoop + } + ``` + +2. **Keep break/continue conditions simple**: + ```kotlin + // โœ… Simple and clear + if (item == target) break + + // โŒ Complex condition + if (item == target && !isProcessed && isValid) break + ``` + +3. **Document complex control flow**: + ```kotlin + // Skip invalid entries and stop at sentinel + for (entry in entries) { + if (!isValid(entry)) continue // Skip invalid + if (entry == SENTINEL) break // Stop at sentinel + process(entry) + } + ``` + +### **โŒ Don'ts** + +1. **Don't overuse break/continue**: + ```kotlin + // โŒ Too many control statements + for (i in 1..10) { + if (i == 1) continue + if (i == 2) continue + if (i == 3) break + if (i == 4) continue + println(i) + } + ``` + +2. **Don't create deeply nested control flow**: + ```kotlin + // โŒ Hard to follow + outer@ for (i in 1..3) { + for (j in 1..3) { + for (k in 1..3) { + if (condition) break@outer + } + } + } + ``` + +## ๐ŸŽฏ What's Next? + +Excellent! You've mastered break and continue statements in Kotlin. Now you're ready to: + +1. **Work with functions** โ†’ [Functions Basics](../functions/01-functions-basics.md) +2. **Explore collections** โ†’ [Arrays](../collections/01-arrays.md) +3. **Understand OOP** โ†’ [Classes and Constructors](../oop/01-classes-constructors.md) +4. **Learn functional programming** โ†’ [Lambdas](../functional-programming/01-lambdas.md) + +## ๐Ÿ“š Additional Resources + +- [Kotlin Returns and Jumps](https://kotlinlang.org/docs/returns.html) +- [Control Flow](https://kotlinlang.org/docs/control-flow.html) +- [Loop Control](https://kotlinlang.org/docs/returns.html#break-and-continue-labels) + +## ๐Ÿ† Summary + +- โœ… You can use break statements to exit loops early +- โœ… You can use continue statements to skip iterations +- โœ… You understand labeled break and continue +- โœ… You can choose the right control statement for your needs +- โœ… You can write more efficient and readable loops +- โœ… You're ready to create sophisticated loop control logic! + +**Keep practicing and happy coding! ๐ŸŽ‰** + diff --git a/docs/control-flow/06-iterators.md b/docs/control-flow/06-iterators.md new file mode 100644 index 0000000..b66405b --- /dev/null +++ b/docs/control-flow/06-iterators.md @@ -0,0 +1,421 @@ +# ๐Ÿ”„ Iterators in Kotlin + +Iterators are the foundation of collection iteration in Kotlin. They provide a way to traverse through collections one element at a time, giving you fine-grained control over how you process data. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Understand what iterators are and how they work +- โœ… Use different types of iterators (forward, backward, bidirectional) +- โœ… Create custom iterators for your own classes +- โœ… Understand the relationship between iterators and collections +- โœ… Use iterator patterns effectively in your code + +## ๐Ÿ” What You'll Learn + +- **Iterator fundamentals** - What iterators are and how they work +- **Iterator interface** - Understanding the Iterator interface +- **Collection iterators** - How collections implement iteration +- **Custom iterators** - Creating iterators for your own classes +- **Iterator patterns** - Common patterns and best practices + +## ๐Ÿ“ Prerequisites + +- Understanding of [Collections](../collections/01-arrays.md) +- Knowledge of [For Loops](03-for-loops.md) +- Familiarity with [Control Flow](01-if-expressions.md) + +## ๐Ÿ’ป The Code + +Let's examine iterators in action: + +**๐Ÿ“ File:** [12_for_loop.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/12_for_loop.kt) + +## ๐Ÿ” Code Breakdown + +### **1. Understanding Iterators** + +#### **What is an Iterator?** +An iterator is an object that allows you to traverse through a collection one element at a time. It provides three main operations: +- **`hasNext()`**: Check if there are more elements +- **`next()`**: Get the next element +- **`remove()`**: Remove the last returned element (optional) + +#### **Basic Iterator Usage** +```kotlin +fun main() { + val numbers = listOf(1, 2, 3, 4, 5) + + // Get iterator from list + val iterator = numbers.iterator() + + // Manual iteration + while (iterator.hasNext()) { + val number = iterator.next() + println("Number: $number") + } +} +``` + +### **2. Iterator Interface** + +#### **Iterator Interface Definition** +```kotlin +interface Iterator { + fun hasNext(): Boolean + fun next(): T + fun remove() // Optional, not always implemented +} +``` + +#### **Using Iterator Methods** +```kotlin +fun demonstrateIterator() { + val fruits = listOf("Apple", "Banana", "Cherry") + val iterator = fruits.iterator() + + println("Iterating through fruits:") + while (iterator.hasNext()) { + val fruit = iterator.next() + println("- $fruit") + } +} +``` + +### **3. Collection Iterators** + +#### **List Iterator** +```kotlin +fun listIteratorExample() { + val numbers = listOf(10, 20, 30, 40, 50) + + // Forward iteration + println("Forward:") + val forwardIterator = numbers.listIterator() + while (forwardIterator.hasNext()) { + println("${forwardIterator.nextIndex()}: ${forwardIterator.next()}") + } + + // Backward iteration + println("\nBackward:") + val backwardIterator = numbers.listIterator(numbers.size) + while (backwardIterator.hasPrevious()) { + println("${backwardIterator.previousIndex()}: ${backwardIterator.previous()}") + } +} +``` + +#### **Mutable List Iterator** +```kotlin +fun mutableIteratorExample() { + val mutableNumbers = mutableListOf(1, 2, 3, 4, 5) + val iterator = mutableNumbers.listIterator() + + while (iterator.hasNext()) { + val number = iterator.next() + if (number % 2 == 0) { + // Remove even numbers + iterator.remove() + } + } + + println("After removing even numbers: $mutableNumbers") +} +``` + +### **4. Custom Iterators** + +#### **Creating a Custom Iterator** +```kotlin +class NumberRange(private val start: Int, private val end: Int) { + fun iterator(): Iterator = object : Iterator { + private var current = start + + override fun hasNext(): Boolean = current <= end + + override fun next(): Int { + if (!hasNext()) { + throw NoSuchElementException() + } + return current++ + } + } +} + +fun customIteratorExample() { + val range = NumberRange(1, 5) + + for (number in range) { + println("Custom range: $number") + } +} +``` + +#### **Iterator with Custom Logic** +```kotlin +class StepIterator( + private val start: Int, + private val end: Int, + private val step: Int +) : Iterator { + private var current = start + + override fun hasNext(): Boolean = current <= end + + override fun next(): Int { + if (!hasNext()) { + throw NoSuchElementException() + } + val result = current + current += step + return result + } +} + +fun stepIteratorExample() { + val stepRange = object : Iterable { + override fun iterator(): Iterator = StepIterator(0, 10, 2) + } + + for (number in stepRange) { + println("Step by 2: $number") + } +} +``` + +### **5. Iterator Patterns** + +#### **Filtering with Iterator** +```kotlin +class FilteringIterator( + private val iterator: Iterator, + private val predicate: (T) -> Boolean +) : Iterator { + private var nextElement: T? = null + private var hasNextElement = false + + override fun hasNext(): Boolean { + if (hasNextElement) return true + + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) { + nextElement = element + hasNextElement = true + return true + } + } + return false + } + + override fun next(): T { + if (!hasNext()) { + throw NoSuchElementException() + } + hasNextElement = false + return nextElement!! + } +} + +fun filteringIteratorExample() { + val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + val evenNumbers = object : Iterable { + override fun iterator(): Iterator = + FilteringIterator(numbers.iterator()) { it % 2 == 0 } + } + + for (number in evenNumbers) { + println("Even number: $number") + } +} +``` + +## ๐ŸŽฏ Key Concepts Explained + +### **1. Iterator vs For Loop** + +**Iterator (Manual Control):** +```kotlin +val iterator = list.iterator() +while (iterator.hasNext()) { + val element = iterator.next() + // Process element +} +``` + +**For Loop (Automatic):** +```kotlin +for (element in list) { + // Process element +} +``` + +**Key Differences:** +- **Iterator**: Manual control, can modify during iteration +- **For Loop**: Automatic, cleaner syntax, can't modify during iteration + +### **2. Iterator Types** + +- **`Iterator`**: Basic forward-only iterator +- **`ListIterator`**: Bidirectional iterator with index access +- **`MutableIterator`**: Iterator that can modify collections +- **Custom Iterators**: User-defined iteration behavior + +### **3. When to Use Iterators** + +**Use Iterators when:** +- You need to modify the collection during iteration +- You want custom iteration logic +- You need bidirectional traversal +- You're implementing custom collection types + +**Use For Loops when:** +- You want simple, readable iteration +- You don't need to modify the collection +- You're doing standard collection traversal + +## ๐Ÿš€ Advanced Iterator Concepts + +### **1. Lazy Iteration** +```kotlin +fun fibonacciIterator(): Iterator = object : Iterator { + private var current = 0L + private var next = 1L + + override fun hasNext(): Boolean = true // Infinite sequence + + override fun next(): Long { + val result = current + current = next + next = result + next + return result + } +} + +fun lazyIterationExample() { + val fibonacci = fibonacciIterator() + + // Take first 10 Fibonacci numbers + repeat(10) { + println("Fibonacci ${it + 1}: ${fibonacci.next()}") + } +} +``` + +### **2. Chaining Iterators** +```kotlin +fun Iterator.filter(predicate: (T) -> Boolean): Iterator { + return FilteringIterator(this, predicate) +} + +fun Iterator.map(transform: (T) -> R): Iterator { + return object : Iterator { + override fun hasNext(): Boolean = this@map.hasNext() + override fun next(): R = transform(this@map.next()) + } +} + +fun chainingExample() { + val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + + val result = numbers.iterator() + .filter { it % 2 == 0 } + .map { it * it } + + for (number in result) { + println("Even squared: $number") + } +} +``` + +## ๐Ÿ’ก Best Practices + +### **1. Iterator Safety** +- Always check `hasNext()` before calling `next()` +- Don't modify collections during iteration (unless using mutable iterators) +- Handle `NoSuchElementException` appropriately + +### **2. Performance Considerations** +- Iterators are memory-efficient for large collections +- Use `forEach` for simple operations +- Consider lazy evaluation for expensive operations + +### **3. Custom Iterator Design** +- Keep iterators simple and focused +- Implement proper error handling +- Consider thread safety if needed + +## ๐Ÿ”ง Common Pitfalls + +### **1. Concurrent Modification** +```kotlin +// โŒ Wrong - Concurrent modification +val list = mutableListOf(1, 2, 3, 4, 5) +for (i in list) { + if (i % 2 == 0) { + list.remove(i) // Throws ConcurrentModificationException + } +} + +// โœ… Correct - Use iterator +val list = mutableListOf(1, 2, 3, 4, 5) +val iterator = list.listIterator() +while (iterator.hasNext()) { + val i = iterator.next() + if (i % 2 == 0) { + iterator.remove() // Safe removal + } +} +``` + +### **2. Infinite Iterators** +```kotlin +// โŒ Wrong - Infinite loop +val infiniteIterator = object : Iterator { + override fun hasNext(): Boolean = true + override fun next(): Int = 1 +} + +// Always have a termination condition +val limitedIterator = object : Iterator { + private var count = 0 + private val limit = 10 + + override fun hasNext(): Boolean = count < limit + override fun next(): Int = ++count +} +``` + +## ๐Ÿ“š Summary + +Iterators are powerful tools that give you fine-grained control over collection iteration. They're essential for: +- **Custom iteration logic** +- **Modifying collections during iteration** +- **Implementing custom collection types** +- **Advanced iteration patterns** + +## ๐ŸŽฏ Practice Exercises + +1. **Basic Iterator**: Create an iterator that counts from 1 to 10 +2. **Filter Iterator**: Build an iterator that only returns even numbers +3. **Custom Collection**: Implement a custom collection with its own iterator +4. **Bidirectional Iterator**: Create an iterator that can go both forward and backward + +## ๐Ÿ”— Related Topics + +- [For Loops](03-for-loops.md) - Automatic iteration +- [Collections](../collections/01-arrays.md) - Data structures +- [Control Flow](01-if-expressions.md) - Program flow control +- [Functions](../functions/01-functions-basics.md) - Function fundamentals + +## ๐Ÿ“– Additional Resources + +- [Official Kotlin Collections Documentation](https://kotlinlang.org/docs/collections-overview.html) +- [Iterator Interface](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-iterator/) +- [Collection Iteration](https://kotlinlang.org/docs/iterators.html) + +--- + +**Next Lesson**: [For Loops](03-for-loops.md) - Learn how for loops use iterators internally + +**Happy coding with Iterators! ๐Ÿš€** diff --git a/docs/control-flow/07-labelled-loops.md b/docs/control-flow/07-labelled-loops.md new file mode 100644 index 0000000..837b7d6 --- /dev/null +++ b/docs/control-flow/07-labelled-loops.md @@ -0,0 +1,543 @@ +# ๐Ÿท๏ธ Labelled Loops in Kotlin + +Labelled loops are a powerful feature in Kotlin that allows you to control nested loops with precision. They're especially useful when you need to break out of or continue from specific loops in complex nested structures. + +## ๐Ÿ“‹ Learning Objectives + +By the end of this lesson, you will be able to: +- โœ… Understand what labelled loops are and when to use them +- โœ… Use labels with break and continue statements +- โœ… Control nested loops effectively +- โœ… Write cleaner, more readable nested loop code +- โœ… Avoid common pitfalls with labelled loops + +## ๐Ÿ” What You'll Learn + +- **Loop labels** - How to label loops for identification +- **Labelled break** - Breaking out of specific loops +- **Labelled continue** - Continuing specific loops +- **Nested loop control** - Managing complex loop structures +- **Best practices** - When and how to use labels effectively + +## ๐Ÿ“ Prerequisites + +- Understanding of [For Loops](03-for-loops.md) +- Knowledge of [While Loops](04-while-loops.md) +- Familiarity with [Break and Continue](05-break-continue.md) + +## ๐Ÿ’ป The Code + +Let's examine labelled loops in action: + +**๐Ÿ“ File:** [15_break_keyword.kt](https://github.com/gpl-gowthamchand/KotlinTutorial/blob/feature/documentation-improvements/src/15_break_keyword.kt) + +## ๐Ÿ” Code Breakdown + +### **1. Basic Labelled Loops** + +#### **What are Labels?** +A label is an identifier followed by `@` that you can use to mark loops, expressions, or functions. When used with `break` or `continue`, it allows you to control which specific loop to break out of or continue. + +#### **Label Syntax** +```kotlin +fun main() { + // Label the outer loop + outer@ for (i in 1..3) { + for (j in 1..3) { + if (i == 2 && j == 2) { + // Break out of the outer loop + break@outer + } + println("i=$i, j=$j") + } + } + println("Outer loop finished") +} +``` + +**Output:** +``` +i=1, j=1 +i=1, j=2 +i=1, j=3 +i=2, j=1 +Outer loop finished +``` + +### **2. Labelled Break Examples** + +#### **Breaking Out of Nested Loops** +```kotlin +fun findElementExample() { + val matrix = arrayOf( + intArrayOf(1, 2, 3), + intArrayOf(4, 5, 6), + intArrayOf(7, 8, 9) + ) + + val target = 5 + var found = false + + // Label the outer loop + search@ for (row in matrix.indices) { + for (col in matrix[row].indices) { + if (matrix[row][col] == target) { + println("Found $target at position [$row][$col]") + found = true + // Break out of both loops + break@search + } + } + } + + if (!found) { + println("$target not found in matrix") + } +} +``` + +#### **Complex Nested Structure** +```kotlin +fun complexNestedExample() { + val data = listOf( + listOf(1, 2, 3), + listOf(4, 5, 6), + listOf(7, 8, 9) + ) + + process@ for (list in data) { + for (item in list) { + if (item < 0) { + println("Found negative number: $item") + // Skip processing this entire list + continue@process + } + + if (item == 0) { + println("Found zero, stopping all processing") + // Stop processing all lists + break@process + } + + println("Processing: $item") + } + println("Finished processing list") + } +} +``` + +### **3. Labelled Continue Examples** + +#### **Continuing Specific Loops** +```kotlin +fun continueExample() { + val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + + outer@ for (i in 0 until numbers.size) { + if (i % 2 == 0) { + // Skip even indices + continue@outer + } + + for (j in 0 until i) { + if (j == 3) { + // Skip to next iteration of outer loop + continue@outer + } + println("Processing i=$i, j=$j") + } + + println("Completed processing for i=$i") + } +} +``` + +#### **Matrix Processing with Continue** +```kotlin +fun matrixProcessingExample() { + val matrix = arrayOf( + intArrayOf(1, 2, 3, 4), + intArrayOf(5, 6, 7, 8), + intArrayOf(9, 10, 11, 12) + ) + + row@ for (row in matrix.indices) { + var rowSum = 0 + + for (col in matrix[row].indices) { + val value = matrix[row][col] + + if (value < 0) { + println("Skipping negative value in row $row") + // Skip this entire row + continue@row + } + + if (value == 0) { + println("Found zero in row $row, column $col") + // Skip this element but continue with the row + continue + } + + rowSum += value + } + + println("Row $row sum: $rowSum") + } +} +``` + +### **4. Advanced Labelled Loop Patterns** + +#### **Multiple Labels** +```kotlin +fun multipleLabelsExample() { + val data = listOf( + listOf(1, 2, 3), + listOf(4, 5, 6), + listOf(7, 8, 9) + ) + + outer@ for (i in data.indices) { + middle@ for (j in data[i].indices) { + inner@ for (k in 0..2) { + val value = data[i][j] + k + + when { + value < 0 -> { + println("Negative value, skip inner loop") + continue@inner + } + value> 10 -> { + println("Value too high, skip middle loop") + continue@middle + } + value == 5 -> { + println("Found target value, exit all loops") + break@outer + } + else -> { + println("Processing value: $value") + } + } + } + } + } +} +``` + +#### **Conditional Labelling** +```kotlin +fun conditionalLabellingExample() { + val shouldUseLabels = true + + if (shouldUseLabels) { + labelled@ for (i in 1..5) { + for (j in 1..5) { + if (i * j> 20) { + println("Product too large, breaking outer loop") + break@labelled + } + println("i=$i, j=$j, product=${i * j}") + } + } + } else { + // Regular nested loops without labels + for (i in 1..5) { + for (j in 1..5) { + if (i * j> 20) { + println("Product too large, breaking inner loop only") + break + } + println("i=$i, j=$j, product=${i * j}") + } + } + } +} +``` + +### **5. Real-World Examples** + +#### **Game Board Processing** +```kotlin +fun gameBoardExample() { + val board = Array(8) { Array(8) { 0 } } + + // Place some pieces + board[0][0] = 1 // White piece + board[7][7] = 2 // Black piece + + // Find all pieces of a specific type + val targetPiece = 1 + val positions = mutableListOf>() + + search@ for (row in board.indices) { + for (col in board[row].indices) { + if (board[row][col] == targetPiece) { + positions.add(Pair(row, col)) + + // If we found enough pieces, stop searching + if (positions.size>= 3) { + break@search + } + } + } + } + + println("Found ${positions.size} pieces of type $targetPiece") + positions.forEach { (row, col) -> + println("Position: [$row][$col]") + } +} +``` + +#### **Data Validation** +```kotlin +fun dataValidationExample() { + val users = listOf( + mapOf("name" to "Alice", "age" to 25, "email" to "alice@example.com"), + mapOf("name" to "Bob", "age" to -5, "email" to "invalid-email"), + mapOf("name" to "Charlie", "age" to 30, "email" to "charlie@example.com") + ) + + val validUsers = mutableListOf