Image for post
Image for post

#31DaysOfKotlin — Week 2 Recap

Sean McQuillan
Apr 12, 2018 · 5 min read

Day 8: Visibility

// public by default
val isVisible = true
// only in the same file
private val isHidden = true
// internal to compilation ‘module’
internal val almostVisible = true
class Foo {
// public by default
val isVisible = true
// visible to my subclasses
protected val isInheritable = true
// only in the same class
private val isHidden = true
}

Day 9: Default arguments

// parameters with default values
class BulletPointSpan(
private val bulletRadius: Float = DEFAULT_BULLET_RADIUS,
private val gapWidth: Int = DEFAULT_GAP_WIDTH,
private val color: Int = Color.BLACK
) {…}
// using only default values
val bulletPointSpan = BulletPointSpan()
// passing a value for the first argument, others default
val bulletPointSpan2 = BulletPointSpan(
resources.getDimension(R.dimen.radius))
// using a named parameter for the last argument, others default
val bulletPointSpan3 = BulletPointSpan(color = Color.RED)

Day 10: Sealed classes

sealed class NetworkResult
data class Success(val result: String): NetworkResult()
data class Failure(val error: Error): NetworkResult()
// one observer for success and failure
viewModel.data.observe(this, Observer<NetworkResult> { data ->
data ?: return@Observer // skip nulls
when(data) {
is Success -> showResult(data.result) // smart cast to Success
is Failure -> showError(data.error) // smart cast to Failure
}
})
// use Sealed classes as ViewHolders in a RecyclerViewAdapter
override fun onBindViewHolder(
holder: SealedAdapterViewHolder?, position: Int) {
when (holder) { // compiler enforces handling all types
is HeaderHolder -> {
holder.displayHeader(items[position]) // smart cast here
}
is DetailsHolder -> {
holder.displayDetails(items[position]) // smart cast here
}
}
}
sealed class DetailItemClickEvent
data class DetailBodyClick(val section: Int): DetailItemClickEvent()
data class ShareClick(val platform: String): DetailItemClickEvent()
data class DeleteClick(val confirmed: Boolean):
DetailItemClickEvent()
class MyHandler : DetailItemClickInterface {
override fun onDetailClicked(item: DetailItemClickEvent) {
when (item) { // compiler enforces handling all types
is DetailBodyClick -> expandBody(item.section)
is ShareClick -> shareOn(item.platform)
is DeleteClick -> {
if (item.confirmed) doDelete() else confirmDetele()
}
}
}
}

Day 11: Lazy

val preference: String by lazy {
sharedPreferences.getString(PREFERENCE_KEY)
}

Day 12: Lateinit

class MyActivity : AppCompatActivity() {
// non-null, but not initalized
lateinit var recyclerView: RecyclerView

override fun onCreate(savedInstanceState: Bundle?) {
// …
// initialized here
recyclerView = findViewById(R.id.recycler_view)
}
}

Day 13: Require and check

fun setName(name: String) {
// calling setName(“”) throws IllegalArgumentException
require(name.isNotEmpty()) { “Invalid name” }

// …
}
fun User.logOut(){
// When not authenticated, throws IllegalStateException
check(isAuthenticated()) { “User $email is not authenticated” }
isAuthenticated = false
}

Day 14: Inline

// define an inline function that takes a function argumentinline fun onlyIf(check: Boolean, operation: () -> Unit) {
if (check) {
operation()
}
}
// call it like this
onlyIf(shouldPrint) { // call: pass operation as a lambda
println(“Hello, Kotlin”)
}
// which will be inlined to this
if (shouldPrint) { // execution: no need to create lambda
println(“Hello, Kotlin”)
}

Android Developers

The official Android Developers publication on Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store