Skip to content

Instantly share code, notes, and snippets.

@sys1yagi
Last active June 7, 2017 08:50
Show Gist options
  • Save sys1yagi/83453d2de50573c702abcabbf759eb22 to your computer and use it in GitHub Desktop.
Save sys1yagi/83453d2de50573c702abcabbf759eb22 to your computer and use it in GitHub Desktop.
object, companion object, top level(package level)の使い分け

object

シングルトンの代替え (Dagger通さなくてもいいやつ)

companion object

staticの代替え

例えばHogeActivity.createIntent()など あと定数とかね

class MainActivity : AppCompatActivity() {
  companion object {
    const val HOGE_REQUEST_CODE = 11111
    fun createIntent(context: Context) =
            Intent(context, MainActivity::class.java)
  }
}

top level(package level)

汎用的な拡張関数、標準ライブラリレイヤの拡張のようなもの

汎用的な拡張関数だと

fun View.gone() {
    visibility = View.GONE
}

fun View.visible() {
    visibility = View.VISIBLE
}

fun View.invisible() {
    visibility = View.INVISIBLE
}

標準ライブラリレイヤの拡張のようなものだと

fun requireEitherIsNotNull(vararg args: Any?) {
    args.forEach {
        if (it != null) {
            return
        }
    }
    throw IllegalArgumentException("Either one must be non-null.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment