Guía completa para la delegación en Kotlin – Tutoriales de Android Studio



La delegación es un concepto en software que nos permite delegar trabajo de un objeto a otro y se ve comúnmente como una alternativa a la herencia. En este video, te mostraré cómo puedes aprovecharlo en tu proyecto de Android. ⭐ Obtenga certificados para su trabajo futuro ⭐ Ahorre incontables horas de tiempo ⭐ Garantía de devolución del 100 % del dinero en 30 días ⭐ Conviértase en un desarrollador profesional de Android ahora: suscríbase a mi boletín informativo GRATUITO para obtener consejos regulares sobre Android, Kotlin y arquitectura. Únase a este canal para obtener acceso a los beneficios: Obtenga el código fuente de este video aquí: Únase a mi servidor de Discord: Consejos de codificación regulares en mi página de Instagram: Consulte mi GitHub: ¿Le gusta mi contenido gratuito? Aquí puedes ofrecerme un café:

Compruebe también

Desarrollo de aplicaciones web móviles (Android studio)

Mi primera aplicación.. Aplicación móvil de restaurante.

42 comentarios

  1. Quick question: How do you like having quiet background music in tutorial videos like this one? Fits well or rather distracting? Thanks!!

  2. You are a wizard))))

    FANTASTIC

  3. Created today a class to handle Otp Auth with firebase. Previously, it was a method inherited using a base activity, now whe are using delegate, and its clear that the single responsability principle its achieved with delegation.

  4. This concept seems similar to Mixins !

  5. Very cool video. So multiple inheritance in Kotlin , yahooo 😀😇

  6. Nice,Please post more kotlin videos

  7. Hello Philipp first of all, I really liked the video and the explanation was really good. I have been watching your videos from the very start and it has helped me alot. Have you heard about the Kotlin/js, which is getting pretty much popular these days, I guess that would be interesting to look into.

  8. How come Mr lackner never published any app on the Playstore with all this knowledge and confusing thoughts on what code to implement? We developers have endure his pesky and fine-tuning videos on so irrelevant maybe importance topics. Yet too deep for his listeners, he keeps on refining..

  9. If anyone wonders why the "3" was not printed – because Philipp filtered "Hello World"

  10. Need explanation with example

  11. I immediately subscribed just after wathcing this one video. 🙂

  12. Thank you for this video! It helps me a lot, but is it also possible to combine Delgation with DI? I would like to pass some UseCases on the LifecycleEventObserver.

  13. Wow! Great video! How create a unit test for MyLazy deliegate?

  14. Delete anything that is not marking sense, please 🙏.

  15. Nice video…..😃…. Thanks

  16. Hello Philipp! I've recently discovered your channel and started learning from your videos. I appreciate that you're teaching actual stuff/skills that are needed to land a job instead of showing only the basics and putting all the important bits behind a paywall. You are awesome.
    Can I ask for a favor though? It's about how you record your audio. As you might have noticed, your mic is picking up a lot of mouth noise. There are ways to eliminate it. For starters, turn down your mic's gain/sensitivity till there's no background noise. Then, turn it down a bit more while speaking so that it picks up your voice but hardly any mouth noises. It's not a problem if the audio level is low, you can amplify it in post production. Talking loudly is important and it helps; as this is how we have conversations in real life. We don't put our ears against the speaking person's mouth, right? There is long enough distance between us and he/she talks loudly enough so that we don't here those noises at all. Oh, drinking some water before speaking also helps. Make sure you're hydrated!
    Why is this important? Well, maybe not important to the majority but when it comes to unwanted sounds, I'm a bit more sensitive than others, I can't help it. I was watching someone else's android programming tutorials before yours, and I had to extract the audio from each video, open them up in audacity, painstakingly delete all the breathing sounds and those INFURIATING swallows, then merge the clean audio with the video track into a file that's much better for my sanity. Otherwise it was driving me so crazy that I wanted to bang my head against the keyboard.

    Anyways, I appreciate the work you're doing again and if you can do as I asked, you'll be even more awesome. Cheers.

  17. How much will it cost to enroll your "The Ultimate PL Course Bundle" online course. Can you convert it in Indian currency and let me know.

  18. great stuff! thank you for your great effort

  19. Highly recommended this From Sri lanka

  20. Philipp how can I perform unit test of activities like these? Is any way to mock this delegations?

  21. got me worried there for a sec..my dad is a millionaire

  22. Hey Philipp, thanks for your video! I have a little missundestanding – why we can't just inject our AnalyticsImpl and DeepLinksHandlerImpl and use them as regular properties? This approach will have same functioanlity and performance, but keeps your activity cleaner because you don't need delegate anything to it.
    For example – if you have any constructor parameters in your Impls delegators you will have to provide them all right in activity. Like Activity : ComponentActivity, Analytics by AnalyticsImpl(some additional parameters creation)
    Really would be glad to see your answer!

  23. You're my God

  24. I agree, base activies are an antipattern they end up being dumps for anything. Favour composition over inheritance.

  25. saying not using inheritance is not correct. you are still using inheritance but delegating the implementation to other class. activity is still inheriting analyicsloger interface.

  26. How wood Hilt injected classes effect this?

  27. Nice Information. Thank you.❤

  28. Great video! Really useful. If I understood correctly, then this Kotlin delegation works exactly the same as the delegation in Swift (?). This will be really useful to make some implementation similar, since I feel Swift and Kotlin already look quite similar!

  29. I'm a little confused with interface segregation principle, Is not the same?

  30. Best explainer I have ever seen. Thanks @Philipp

  31. How to include native code such as rust or Go in compose?

  32. Super cool video. I feel like after several smaller projects, I'm starting to get better at visualizing separation of concerns across different object types, and how we can link them together.

  33. Thank you for this excellent video but, the first example (AnalytiycsLogger) related to Class Delagation given in this video is not relevant because you could simply use composition by calling: owner.lifecycle.addObserver(AnalytiycsLoggerImpl())

    # The rule is:
    Use class delegation with care. Among the three choices—inheritance, composition and class delegation—try composition first. It’s the simplest approach and solves the majority of use cases. Inheritance is necessary when you need a hierarchy of types, to create relationships between those types. Class delegation can work when those options don’t.

    # For Example:
    You cannot inherit a class when the superclass is not open, or if your new class is already extending another class. Class delegation releases you from these and other limitations. (delegation solves the need for multiple inheritance).

    # Double inheritance example form "Atomic kotlin" Book:
    – Code:

    interface Rectangle {
    fun paint(): String
    }

    class ButtonImage(
    val width: Int,
    val height: Int
    ): Rectangle {
    override fun paint() = "painting ButtonImage($width, $height)"
    }

    interface MouseManager {
    fun clicked(): Boolean
    fun hovering(): Boolean
    }

    class UserInput : MouseManager {
    override fun clicked() = true
    override fun hovering() = true
    }

    class Button(
    val width: Int,
    val height: Int,
    var image: Rectangle = ButtonImage(width, height),
    private var input: MouseManager = UserInput()
    ): Rectangle by image, MouseManager by input

    fun main() {
    val button = Button(10, 5)
    // Can upcast to both delegated types:
    val rectangle: Rectangle = button
    val mouseManager: MouseManager = button
    }

    – Explanation:
    The class Button implements two interfaces: Rectangle and MouseManager. It can’t inherit from implementations of both ButtonImage and UserInput, but it can delegate to both of them.

    Notice that the definition for image in the constructor argument list is both public and a var. This allows the client programmer to dynamically replace the ButtonImage.

    The last two lines in main() show that a Button can be upcast to both of its delegated types.
    This was the goal of multiple inheritance, so delegation effectively solves the need for multiple inheritance.

  34. hi philip, I'm very grateful every time your video uploaded, almost your videos have impact for my code. lately I have a trouble that bothering me, can you please make video how to properly make moving view from current view to previous view with lazy column/row in compose (like change focus or some thing like one page landing page if you click a button and the view moving according its id). cause what I've done was make a calculated position and remember them every time new item loaded, and make it so laggy.

    I hope you would help me for this problem.

  35. Having fun programming? Just "override fun" 😉

  36. Good video, Philipp! Question: You created interfaces, then never really used them. If this were dependency injection, then you wasted the opportunity to substitute different implementations – for example in testing. How does the use of an Interface help things? Seems like the Activity is hopelessly coupled to particular implementations…

  37. Thanks by MattGraves

  38. 10:00 so it is same like having the deeplinkhandler or the analytics logger injected in the activity class.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *