Skip to content

Instantly share code, notes, and snippets.

View Kotlin_implicit_return2.kt
.map {
with(createRequest(Type.NEXT, it, data)) {
val keywords = // ...
copy(keywords = keywords)
}
}
View Kotlin_implicit_type.kt
fun returnsUnit() {
methodReturningBoolean()
}
fun returnsAnImplicitBoolean() = methodReturningBoolean()
private fun methodReturningBoolean() = true
View Kotlin_implicit_return.kt
fun alwaysReturnsNull(position: Int): String? {
if ((position % 10) == 0) {
when (position) {
10 -> "one"
20, 30 -> "two"
else -> "three"
}
}
return null
}
View Repository_companion_object.kt
class Repository {
init{
}
companion object {
private val CACHE = TimeUnit.HOURS.toSeconds(4)
}
}
View MyActivity_onCreate.kt
fun requireNotNulls(vararg any: Any?) {
any.forEach {
requireNotNull(value = it)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requireNotNulls(id1, id2)
}
View MyActivity.kt
const val ID = "id"
class MyActivity : Activity() {
private val id1 by extra<String>(ID) // String?
private val id2 by extraNotNull<String>(ID) // String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requireNotNull(id1, id2)
View _Fragment_LazyExtra.kt
inline fun <reified T: Any> Fragment.extra(key: String, default: T? = null) = lazy {
val value = arguments?.get(key)
if (value is T) value else default
}
inline fun <reified T: Any> Fragment.extraNotNull(key: String, default: T? = null) = lazy {
val value = arguments?.get(key)
requireNotNull(if (value is T) value else default) { key }
}
View _Activity_LazyExtra.kt
inline fun <reified T: Any> Activity.extra(key: String, default: T? = null) = lazy {
val value = intent?.extras?.get(key)
if (value is T) value else default
}
inline fun <reified T: Any> Activity.extraNotNull(key: String, default: T? = null) = lazy {
val value = intent?.extras?.get(key)
requireNotNull(if (value is T) value else default) { key }
}
View MainViewModel.kt
@UiThread
fun getUsers(context: Context): LiveData<List<User>> {
if (!::users.isInitialized) {
users = MutableLiveData()
Coroutines.ioThenMain({
DataManager.getUsers(context)
}) {
users.value = it
}
}
View DataManager.kt
object DataManager {
@WorkerThread
fun dummy(context: Context) {
with(MyDatabase.get(context)) {
users().insert(User(login = "user.name"))
projects().insert(Project(name = "project.name"))
notifications().insert(Notification(msg = "created"))
}
}