Teagan Glenn
Teagan42
Senior Software Engineer
Aetna
/*
* Kotlin let
*/
fun setActivityTitle(title: String?): Fragment? =
title?.let {
activity?.title = it
this
}
// With parameter name override
fun setActivityTitle(title: String?): Fragment? =
title?.let { newTitle ->
{
activity?.title = newTitle
this
}() // Since it's a block, we need to evaluate it
}
/*
* Kotlin apply
*/
fun setActivityTitle(title: String?) = title?.apply { activity?.title = this }
/*
* Kotlin run
*/
fun setActivityTitle(title: String?) = title?.run { activity?.title = this }
/*
* Kotlin also
*/
fun setActivityTitle(title: String?): String? =
title?.also { activity?.title = it }
// With parameter name override
fun setActivityTitle(title: String?): String? =
title?.also { newTitle -> activity?.title = newTitle }
Syntactic sugar for run without an operant
Safely closes the operant upon completion of the block expression, regardless of exception
/*
* Kotlin with
*/
override fun onViewCreated() {
with(my_text_view) {
text = "My Default Text"
setOnClickListener = textClickListener
setOn
}
}
/*
* Kotlin use
*/
fun getTestData(context: Context, gson: Gson, jsonAssetName: String) =
context.resources.assets.open().use {
gson.fromJson(InputStreamConverter.getInputStreamAsString(this), SomeDataType::class.java)
}
infix fun Int.mod(divisor: Int): Int = this % divisor
fun calculateChange(amount: Int) = amount mod 100
//--------------------\\
inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> Unit) {
val fragmentTransaction = beginTransaction()
fragmentTransaction.func()
fragmentTransaction.commit()
}
fun setFragment(fragment: Fragment) {
supportFragmentManager.inTransaction {
replace(contentViewId, fragment, fragment::class.simpleName)
addToBackStack.ifTrue { addToBackStack(fragment::class.simpleName) }
}
}
//--------------------\\
fun String?.toUri(): Uri? =
if (this == null) null
else try {
Uri.parse(this)
} catch (e: Exception) {
Timber.e(e)
null
}
fun goToUrl(address: String?) = startActivity(Intent(Intent.ACTION_VIEW, address?.toUri()))