Kotlin Advanced KeyWords #2 Reified : The reified keyword in Kotlin is a powerful tool that allows you to access the type information of a generic parameter at runtime. Normally, generic type parameters in Kotlin are erased during compilation due to type erasure, meaning the type information is not available at runtime. However, by using the reified keyword in conjunction with an inline function, Kotlin allows you to preserve this type information. * When and Why Use reified You use reified when: You need to access or check the type of a generic parameter at runtime (e.g., for type checks or casting). You want to simplify type-specific operations, like creating instances of a type or filtering collections by type. reified works only within inline functions because the function body is substituted directly at *usecases 1- Basic usage : check type inline fun <reified T> isOfType(value: Any): Boolean { return value is T } // Usage println(isOfType<String>("Hello")) // true println(isOfType<Int>("Hello")) // false 2- Instance Creation You can use reified to create new instances of the generic type: inline fun <reified T> createInstance(): T { return T::class.java.getDeclaredConstructor().newInstance() } // Usage data class Example(val name: String = "Default") val instance = createInstance<Example>() println(instance) #kotlin_advanced_keywords
Osama Saqr’s Post
More Relevant Posts
-
🌟 Simplify Complex Types in Kotlin with typealias! 🌟 In Kotlin, we can use the typealias keyword to make complex types more readable and concise. In this example, we’ve created a custom alias ItemList for a complex type Map<String, List<Pair<Int, String>>>. This structure represents a map where each category (like "Fruits" or "Vegetables") holds a list of items, each having an ID and a name. 📌 Code Breakdown: => typealias ItemList: Simplifies the complex map structure. => The printItems() function loops through the categories and prints the ID and name of each item. => This clean and readable approach helps avoid verbose code when dealing with complex data structures. 💡 Tip: typealias is perfect for when you need to repeatedly use complex types, improving both code readability and maintainability.
To view or add a comment, sign in
-
Kotlin 2.0 has been released today (but not official announcement yet). One of the more interesting features it brings is the “context receivers”, it’ll definitely change the way we write APIs in our software and increase developer experience 😄 One year ago i wrote about Kotlin Context receivers and how it can be used with a real word example on Scope safety in Compose. It can make developers able to add scoped modifiers to an existing (internal) compose object. You can check it out here https://lnkd.in/dkMR8qgC Ps : This feature can even change the way we are doing dependency injection, hopefully i’ll have some time to write about it.
To view or add a comment, sign in
-
🌟 Day 2: Variables and Data Types in Kotlin 🌟 Understanding Variables in Kotlin 📝 Kotlin provides two ways to declare variables: • val: Immutable (read-only). Once assigned, its value cannot be changed. • var: Mutable. Its value can be modified later. val name = "John Doe" // Immutable var age = 25 // Mutable Exploring Basic Data Types in Kotlin 📊 Kotlin supports a variety of data types: • Int: Represents whole numbers (e.g., 1, 2, 3). • Double: Represents decimal numbers (e.g., 3.14). • String: Represents text (e.g., "Hello"). • Boolean: Represents true or false values. Type Inference in Kotlin 💡 Kotlin is smart! It automatically infers the type of a variable based on the assigned value: val language = "Kotlin" // Inferred as String var number = 42 // Inferred as Int Did You Know? 🤩 Using val over var wherever possible makes your code safer and easier to maintain by reducing unintended changes! 🔒 Question: Do you prefer using val or var in your projects, and why? Let's discuss! 💬 Stay tuned for Day 3: Operators in Kotlin! ➕➖
To view or add a comment, sign in
-
What is the difference between "const" and "val" in kotlin ? both val and const are used to define immutable values, but they have different use cases and limitations. val: • Immutable Runtime Constants: A val (short for value) is a read-only variable. Once it’s initialized, its value cannot be changed. However, the value can be assigned at runtime. • Initialization: val can be initialized in the constructor of a class or in a block of code. It can hold any value, including those determined at runtime. • Example: val age = 25 // Initialized when the code is executed . const: • Compile-Time Constants: const is a keyword used to define constants that are known at compile time. This means the value must be determined and assigned at the time of compilation. • Top-Level or object Declaration: const can only be used with val variables that are declared at the top level of a Kotlin file, inside an object, or in a companion object. It cannot be used in a local function or inside a class body. • Type Restrictions: const can only be used with primitive types (e.g., String, Int, Boolean, etc.) and String. • Example: const val PI = 3.14159 // Compile-time constant
To view or add a comment, sign in
-
🌟 Day 20: Generics in Kotlin 🌟 What Are Generics? 🧬 Generics allow you to write flexible and reusable code that works with any data type while ensuring type safety at compile time. Using Generics in Kotlin 🔍 • Generic Functions: Functions that work with any type: fun <T> printItem(item: T) { println(item) } printItem(42) // Output: 42 printItem("Kotlin") // Output: Kotlin • Generic Classes: Classes that can handle different types: class Box<T>(val content: T) val intBox = Box(123) val stringBox = Box("Hello") Type Constraints in Generics 🔒 Restrict types using constraints to ensure safety and compatibility: fun <T : Number> addNumbers(a: T, b: T): Double { return a.toDouble() + b.toDouble() } println(addNumbers(3, 5)) // Output: 8.0 Why Use Generics? 🤔 • Reusability: Write code once and use it with multiple types. • Type Safety: Catch type-related errors at compile time. • Flexibility: Create versatile data structures and algorithms. Did You Know? 🤩 Generics in Kotlin are reified in inline functions, allowing type information to be used at runtime! 🔍 Question: How do you use generics in your Kotlin projects to keep your code flexible? Share your examples! 💡 Stay tuned for Day 21: Concurrency with Coroutines in Kotlin! ⚡
To view or add a comment, sign in
-
🌟 Kotlin Quick Tip #15: Simplify Your Code with Destructuring Declarations 🌟 Kotlin's destructuring declarations allow you to unpack a single object into several variables in a concise manner, improving both readability and conciseness of your code. Explanation for the given example here: -- Data Class: `User` is a Kotlin data class with properties `id`, `name`, and `email`. Destructuring Declaration: `val (id, name, email) = user` unpacks the properties of `User` into three variables: `id`, `name`, and `email`. Usability: Each property can then be used independently in your function, which simplifies accessing the members of the object. Benefits: -- Clarity: Immediately understand which properties are being used from an object. Less Code: Eliminate the need for multiple lines of getter calls. Efficient Assignments: Quickly assign multiple variables from a complex object in a single, readable line. Implement destructuring in your project to notably reduce boilerplate code and enhance the clarity of operations that involve complex objects. This feature is especially useful when working with data models or API responses where only selected properties of an object are required. #Kotlin #ProgrammingTips #DestructuringDeclarations #CodeSimplification
To view or add a comment, sign in
-
New Post: Resolving Compile Error: “Const ‘val’ is only allowed on top level, in named objects, or in companion objects” in Kotlin
Resolving Compile Error: “Const ‘val’ is only allowed on top level, in named objects, or in companion objects” in Kotlin | Baeldung on Kotlin
baeldung.com
To view or add a comment, sign in
-
Inline Classes in Kotlin! 🚀 Are you tired of writing tons of code for simple data types? 𝗜𝗻𝗹𝗶𝗻𝗲 𝗖𝗹𝗮𝘀𝘀𝗲𝘀𝗅 These guys act like wrappers but vanish at compile time, leaving the raw data behind. 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀: - 𝗟𝗲𝘀𝘀 𝗖𝗼𝗱𝗲, 𝗠𝗼𝗿𝗲 𝗙𝘂𝗻: Inline classes streamline your code, making it cleaner and easier to read. - 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲 𝗕𝗼𝗼𝘀𝘁: By ditching object creation, inline classes can make your code faster. - 𝗧𝘆𝗽𝗲 𝗦𝗮𝗳𝗲𝘁𝘆: Inline classes enforce type safety, preventing you from accidentally using the wrong data type. 𝗪𝗵𝗲𝗻 𝘁𝗼 𝗨𝘀𝗲 𝗜𝗻𝗹𝗶𝗻𝗲 𝗖𝗹𝗮𝘀𝘀𝗲𝘀: - You're working with primitive data types like integers or floats. - You want cleaner, more readable code. - Type safety is important (e.g., ensuring a value represents a valid length). 𝗡𝗼𝘁 𝘀𝘂𝗿𝗲 𝗶𝗳 𝗮𝗻 𝗶𝗻𝗹𝗶𝗻𝗲 𝗰𝗹𝗮𝘀𝘀 𝗶𝘀 𝗿𝗶𝗴𝗵𝘁? A regular class might be better for: - Complex data types with multiple properties or behaviors. - Situations where you need to perform additional logic on the data. 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲 𝗖𝗼𝗻𝘀𝗶𝗱𝗲𝗿𝗮𝘁𝗶𝗼𝗻𝘀: Inline classes can significantly improve performance by eliminating unnecessary object allocations. In performance-critical scenarios, this optimization can lead to noticeable speed-ups. Check out this code! This simple inline class is much clearer and avoids extra memory usage.
To view or add a comment, sign in
-
My thought on Clean Code, Chapter 2: Meaningful Names My paraphrase: Name variables, functions, classes, files, directories, packages, event commit messages with INTENT << Important This habit will improve communications within team, and avoid unnecessary explanation to certain codes. When somebody trying to name without intent, jokingly put names or lazily naming something, in the future it will make the code harder to understand, which will damage the performance of the team, caused by the person who working in the code that previously lazily named have to read the code multiple times to understand the meaning of a single variable/function. This can be prevented by Code Reviewer to demand explanation or suggesting more meaningful name, or even better to create a correct name in the beginning. TIPS: In Kotlin, you can create inline value class (previously inline class) that can be useful to improve your code readability. Case: You have a list, are you sure that the list is never empty? do you have to check on every function that requires the data type? (which violates DRY) Solution: write data type to do it for you. Code: value class <T> NonEmptyList(private val list: List<T>) { init { requires(list.isNotEmpty()) // you can make sure that the function that use this class is never empty. } } Photo: An intention revealing label to avoid the parking spot being taken. Still people can violate, but at least the owner already put their intention in it.
To view or add a comment, sign in
-
New Post: Serialize Enum in Retrofit With Kotlin
Serialize Enum in Retrofit With Kotlin | Baeldung on Kotlin
baeldung.com
To view or add a comment, sign in
Senior Full Satck (.Net | Angular)
1moUseful tips