The Also Scope Function Explained (Kotlin)

Поделиться
HTML-код
  • Опубликовано: 14 ноя 2024

Комментарии • 8

  • @MrRahulmalik
    @MrRahulmalik 4 года назад +1

    I tend to use it with Snackbar or Intent like this -
    Intent(this, MainActivity::class.java).also { startActivity(it) }

  • @mauricio0guaruja
    @mauricio0guaruja 3 года назад

    you can use method reference in this case too, .also(::println)

  • @yasminedwedar8651
    @yasminedwedar8651 4 года назад +1

    whats the difference between this and it in this example please can anyone help me ?

    • @CodyEngelCodes
      @CodyEngelCodes  4 года назад

      It has to do with the scope within the curly braces, in all honesty though I generally pick one or the other based on readability. With “it” you can l define the variable to something else so “it” could be defined as “person” if you were working with a Person object for instance. On the other hand “this” cannot be redefined but it can be omitted from the call site so it can make the code more concise but sometimes harder to follow.

    • @mihun4ik
      @mihun4ik 2 года назад

      data class Person(val name: String, val age: Int)
      val examplePerson = Person("Yasmine", 21)
      examplePerson.apply {
      println("$name is $age") // Yasmine is 21
      }
      examplePerson.also {
      println("Person's name is ${it.name}") // Person's name is Yasmine
      }