Android开发经验谈Android开发Android技术知识

与Kotlin有关的31天-第二周

2018-06-30  本文已影响5人  塞上牧羊空许约

第八天:可见性(Visibility)

Kotlin中,一切都是默认为public。当然,它还有一套丰富的可见性修饰符以供使用:private, protected, internal。他们分别在不同程度上降低可见性。

// 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
}

第九天:缺省参数

重载的方法数多到难以控制啦?给函数参数指定一个缺省值吧。还可以用命名参数让代码变得更加可读:

// 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)

第十天:密封类

Kotlin的密封类可以让你轻松地处理错误数据。与LiveData结合时,你可以仅用一个LiveData来表示成功和失败的路径。某种程度上好于使用两个变量吧。

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
  }
})

你也可以在RecyclerView的adapter使用密封类,它们非常适合ViewHolders--有确定的一些类型对应不同的holder。当作为一个表达式使用时,类型没有匹配完全时编译器将会报错。

// 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
    }
  }
}

更深入地探讨下RecyclerViews。如果RecyclerView的item有很多callback,比如详情点击,分享,删除动作时,我们可以使用密封类,
一个使用密封类的callback就可以搞定一切啦。

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()
      }
    }
  }
}

第十一天:Lazy

懒加载是个好东西!延迟开销大的属性初始化动作直到需要使用他们的时候,这时请使用lazy。计算后的值将会被保存以供后面使用

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()
      }
    }
  }
}

第十二天

在Android中,onCreate或者其他回调中初始化对象。Kotin中非空对象必须初始化。怎么办?使用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)
  }
}

第十三天:Require and Check

你的函数实参是有效的么?使用它们之前用require来检查下,
如果它们无效,将会抛出IllegalArgumentException,

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

外部类的状态是否正确呢?使用check来验证。如果检查的值为false将会抛出IllegalStateException

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

第十四天:Inline

迫不及待地想使用lambdas来生成一个新的api?Kotlin允许你指定一个函数为inline----意味着你的调用将会被函数体替代。深呼吸一下,你马上就可以零开销地使用基于lambda的api啦

// define an inline function that takes a function argument
inline 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”)
}

翻译自:#31DaysOfKotlin — Week 2 Recap

上一篇 下一篇

猜你喜欢

热点阅读