Skip to content

Instantly share code, notes, and snippets.

View AkshayChordiya's full-sized avatar
🔱

Akshay Chordiya AkshayChordiya

🔱
View GitHub Profile
@AkshayChordiya
AkshayChordiya / ApplyExample.kt
Last active November 25, 2020 15:56
Example of apply function in Kotlin
val person = Person().apply {
name = "Tony Stark"
age = 52
// More such stuff
}
@AkshayChordiya
AkshayChordiya / UseExample.kt
Created July 6, 2017 04:59
Example of use function in Kotlin
FileReader("input.txt").use {
// Read the file
}
// Automatically closed
@AkshayChordiya
AkshayChordiya / TryWithResource.java
Created July 6, 2017 05:05
Try with resource example in Java
try (FileReader reader = new FileReader("input.txt")) {
// Read the file
} catch (IOException e) {
e.printStackTrace();
}
// Automatically closed
@AkshayChordiya
AkshayChordiya / AlsoExampleWithIt.kt
Created July 6, 2017 05:51
Example of Also function in Kotlin
val person = Person().also {
it.name = "Tony Stark"
it.age = 52
// More such stuff
}
@AkshayChordiya
AkshayChordiya / AlsoExampleWithName.kt
Created July 6, 2017 05:52
Example of Also function with name in Kotlin
val person = Person().also { p ->
p.name = "Tony Stark"
p.age = 52
// More such stuff
}
@AkshayChordiya
AkshayChordiya / TakeIfExample.kt
Created July 7, 2017 04:50
Example of takeIf function in Kotlin
val index = "Kotlin".indexOf('K').takeIf { it > 0 } ?: 0
@AkshayChordiya
AkshayChordiya / TakeUnlessExample.kt
Created July 7, 2017 04:56
Example of takeUnless function in Kotlin
val index = "Kotlin".indexOf('K').takeUnless { it < 0 } ?: 0
@AkshayChordiya
AkshayChordiya / WithExampleReturn.kt
Last active April 4, 2019 12:38
Example of with function with return in Kotlin
val person = with(Person()) {
name = "Tony Stark"
age = 52
// More such stuff
this
}
@AkshayChordiya
AkshayChordiya / UserViewModel.kt
Last active August 17, 2017 09:36
User View Model with LiveData
class UserViewModel() : ViewModel() {
/**
* The user
*/
private var users: LiveData<List<User>>
init {
// Load the user over here
// users = ....
@AkshayChordiya
AkshayChordiya / MainActivity.kt
Last active August 17, 2017 09:36
Main Activity with ViewModel instance and LiveData observe
class MainActivity : LifecycleActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Get the ViewModel instance
val userViewModel = ViewModelProviders.of(this).get(UserViewModel::class.java)
userViewModel.getUsers().observe(this, Observer {
// Update the UI