Instantly share code, notes, and snippets.

View UsingSealedClass.kt
val result = parse(url)
when (result) {
is ParseResult.ParsedData -> analyzeMimeType(result.mimeType)
is ParseResult.Error -> log(result.errorMessage)
}
View ParseSealedClass.kt
private fun parse(url: String): ParseResult {
val result = URL_PARSE_REGEX.find(url)
if(result == null) {
return ParseResult.Error("No match found")
}
val mimeType = result.groupValues[2]
val data = result.groupValues[4]
return ParseResult.ParsedData(data, mimeType)
View SealedClass.kt
sealed class ParseResult
data class Error(val errorMessage: String) : ParseResult()
data class ParsedData(
val data: String,
val mimeType: String) : ParseResult()
View ResultWrapper.kt
class ResultWrapper(
val data: ParsedData? = null,
val errorMessage: String? = null
)
View Caller.kt
val result = parse(url)
if(result.errorMessage != null) {
// error occurred - log error message etc...
} else {
// happy path - use the data. But result.data is nullable 🙄
val mimeType = result.data!!.mimeType
}
View UrlParser.kt
private fun parse(url: String): ParsedData {
val result = URL_PARSE_REGEX.find(url)
if(result == null) {
// what do we do here? Throw an exception? Return null?
}
val mimeType = result.groupValues[2]
val data = result.groupValues[4]
View Activity.kt
taskDao.getAll().observe(this, Observer<List<Task>> {
taskListAdapter.submitList(it)
})
View TaskDiffCallback.kt
class TaskDiffCallback : DiffUtil.ItemCallback<Task>() {
override fun areItemsTheSame(oldItem: Task?, newItem: Task?): Boolean {
return oldItem?.id == newItem?.id
}
override fun areContentsTheSame(oldItem: Task?, newItem: Task?): Boolean {
return oldItem == newItem
}
}
View NewListAdapter.kt
class TaskListAdapter(private val clickListener: (Task) -> Unit) :
ListAdapter<Task, ViewHolder>(TaskDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return ViewHolder(inflater.inflate(R.layout.item_task_row, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position), clickListener)
View OldStyleAdapter.kt
class TaskListAdapter : RecyclerView.Adapter<ViewHolder>() {
private val tasks: MutableList<Task> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return ViewHolder(inflater.inflate(R.layout.item_task_row, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {