Last active
September 5, 2018 20:07
-
-
Save Kamil-Kaminski/279caea50ee5ce11c908a9a176c279b7 to your computer and use it in GitHub Desktop.
This sample shows how to use kotlin .apply() based on fragment instantiating example. There are 4 examples: first in Java, second in Kotlin without apply(), third in Kotlin with one apply(), and last in Kotlin with two apply().
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Java | |
public static DetailsFragment newInstance(int id) { | |
Bundle arguments = new Bundle(); | |
arguments.putInt("id", id); | |
DetailsFragment fragment = new DetailsFragment(); | |
fragment.setArguments(arguments); | |
return fragment; | |
} | |
// Kotlin without apply() | |
companion object { | |
fun newInstance(id: Int): DetailsFragment { | |
val arguments = Bundle() | |
arguments.putInt("id", id) | |
val fragment = DetailsFragment() | |
fragment.setArguments(arguments) | |
return fragment | |
} | |
} | |
// Kotlin with one apply() | |
companion object { | |
fun newInstance(id: Int): DetailsFragment = DetailsFragment().apply { | |
val arguments = Bundle() | |
arguments.putInt("id", id) | |
setArguments(arguments) | |
} | |
} | |
// Kotlin with two apply() | |
companion object { | |
fun newInstance(id: Int): DetailsFragment = DetailsFragment().apply { | |
arguments = Bundle().apply { arguments.putInt("id", id) } | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment