Skip to content

Instantly share code, notes, and snippets.

View ch8n's full-sized avatar
💻
Always on to writing my next article.

Chetan Gupta ch8n

💻
Always on to writing my next article.
View GitHub Profile
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
val binding = MainLayoutBinding.inflate(layoutInflater)
setup(binding)
}
// write binding once and forget ✅
fun setup(binding:MainLayoutBinding) = with(binding) {
textName.text = "ch8n"
val binding = MainLayoutBinding.inflate(layoutInflater)
with(binding) {
textName.text = "ch8n"
textTwitter.text = "twitter@ch8n2"
})
val userName: String
get() = preferenceManager.getInstance()?.getName() ?: getString(R.string.stranger)
val userName: String
get() {
preferenceManager.getInstance()?.run {
getName()
} ?: run {
getString(R.string.stranger)
}
}
val intent = Intent(context, MyActivity::class.java).apply {
// scope to configure object
putExtra("data", 123)
addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
})
startActivity(this@FooActivity,intent)
Intent(context, MyActivity::class.java).apply {
// scope to configure object
putExtra("data", 123)
addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
}).also { intent ->
// scope to consume the object
startActivity(this@FooActivity,intent)
}
class Foo {
var imageFile : File ? = ...
fun deleteImage(){
// 🧐 you can get away for now
imageFile?.let { image ->
if(image.exists()) image.delete()
}
}
}
class Foo {
var imageFile : File ? = ...
fun deleteImage(){
val imageFile = this.imageFile
if(imageFile != null) {
if(imageFile.exists()) imageFile.delete()
}
}
}
fun deleteImage(){
val imageFile : File ? = ...
if(imageFile != null) {
// 👇 smart casted imageFile into non nullable
if(imageFile.exists()) imageFile.delete()
}
}
fun deleteImage(){
var imageFile : File ? = ...
imageFile?.let { // ❌ don't write code like this
if(it.exists()) it.delete()
}
}