ivano
01/09/2020, 8:00 AMif (ocrItem.pattern is DateRegex) {
ocrItem.newValue = result.transformToDefaultDate()
} else {
ocrItem.newValue = result
}
Jérôme Gully
01/10/2020, 9:53 AMsealed class NotificationData(val contactDisplayName: String) {
class Message(contactDisplayName: String, val contentMessage: String) : NotificationData(contactDisplayName)
class Join(contactDisplayName: String) : NotificationData(contactDisplayName)
class File(contactDisplayName: String) : NotificationData(contactDisplayName)
class Audio(contactDisplayName: String) : NotificationData(contactDisplayName)
}
Is there a better way to initialize the contactDisplayName
property ?
contactDisplayName
is defined in the base class and each child class "override" itcorneil
01/10/2020, 7:47 PMJérôme Gully
01/14/2020, 2:50 PMopen class ParticipantsExtension {
companion object {
const val ELEMENT = "participants"
}
open fun getElement() = ELEMENT
fun parse() {
// common code used with ELEMENT from child
}
}
class UpdatedParticipantsExtension : ParticipantsExtension() {
companion object {
const val ELEMENT = "updated-participants"
}
override fun getElement() = ELEMENT
}
class AddedParticipantsExtension : ParticipantsExtension() {
companion object {
const val ELEMENT = "added-participants"
}
override fun getElement() = ELEMENT
}
IS there a better way with no redundant code ?
I must access overridden ELEMENT
as static fiel in an other class, AND use ELEMENT
in the base function parse()
with the overridden valueivano
01/21/2020, 2:21 PMcompanion object {
fun <T> fromData(data: T): Result<T> {
return Result(data, null)
}
fun <T> fromError(error: Throwable): Result<T> {
return when (error) {
is HttpException -> {
if (error.code() in 400..499) {
if (error.code() == 401) AccountStorage().signOut()
mapErrorBody(error, PAErrorModel::class.java)?.let {
return Result(null, it)
} ?: return Result(null, PAErrorModel("", error.localizedMessage))
}
return Result(null, PAErrorModel("", error.localizedMessage))
}
else -> Result(null, error)
}
}
}
arekolek
01/24/2020, 8:30 AM// 1
interface FooFactory {
fun getFoo(): Foo
}
// 2
interface FooFactory : () -> Foo
// 3
interface FooFactory : () -> Foo {
override fun invoke(): Foo
}
Is 2 or 3 something that people do?
(not using a typealias
here, because it wouldn't work with Dagger)Paul Woitaschek
01/25/2020, 3:44 PMmyanmarking
01/28/2020, 2:53 PMvar date: LocalDateTime = from
while (date.isBefore(LocalDateTime.now())) {
getDataFromXXX(date = date)
date = date.plusHours(1)
}
Georgi Naumov
01/29/2020, 8:38 AMtipsy
01/31/2020, 3:30 PMinputStream.apply { skip(from.toLong()) }.use {
var bytesLeft = bytesToWrite
while (bytesLeft != 0) {
val read = it.read(buffer, 0, Math.min(buffer.size, bytesLeft))
outputStream.write(buffer, 0, read)
bytesLeft -= read
}
}
Kashif
02/03/2020, 4:06 PMoverride fun getOrderInfoList(status: String, chainID: String, debugTag: String): Flowable<Result<List<OrderInfo>>> {
logger.d(TAG, "Getting order list for status %s", status)
val fetchFromStorageObservable = storageDataSource.getOrderList(debugTag)
val observeStorageObservable = storageDataSource.observeOrderList(debugTag)
// function which fetches from the local storage and takes a throwable that might be re-thrown if there's no data found locally
val fetchFromStorageOrThrowObservable = fun (t : Throwable) : Observable<Result<List<OrderInfo>>> {
fetchFromStorageObservable.map {
if(it.isEmpty()) {
// re-throw the exception from the Remote source since we got no data from the Local source
throw t
}
it
}
}
val fetchFromRemoteObservable = remoteDataSource.getOrderInfoList(status, chainID).toObservable().onErrorResumeNext { t: Throwable ->
logger.d(TAG, "order list not received from server")
// fallback to the local source
fetchFromStorageOrThrowObservable(t)
}.flatMap {
if (it is Result.Success) {
persisOrderInfoList(it.data)
}
fetchFromStorageObservable
}
return Observable.concat(fetchFromRemoteObservable, observeStorageObservable).toFlowable(BackpressureStrategy.LATEST)
}
Medamine Rihane
02/07/2020, 12:59 PMDaniel
02/08/2020, 12:16 PMfun String.setCharAt(index: Int, char: Char) = StringBuilder(this)
.apply {
setCharAt(index, char)
}.toString()
Googling franticly, but I can't find an inbuild method for thisAlex Woods
02/10/2020, 6:14 PMdata class Foo(val a: String = "hello")
// can I access "hello" somehow, like Foo::class.fields.map { it.defaultValue }
2. What’s the maximum supertype I can use on an annotation? I know annotations can only take certain values (primitives in Java, classes, etc.).
@Target...
annotation class Bar<T>(val value: T) // nope!
annotation class Bar(val value: Any) // nope!
Is there some supertype for anything that is valid in an annotation?Ellen Spertus
02/11/2020, 7:55 PMprivate fun getIntent(utterance: String): Intent =
IntentRunner.processUtterance(utterance)?.let { intent ->
intent.resolveActivityInfo(packageManager, intent.flags)?.let { activityInfo ->
if (activityInfo.exported) intent else null
}
} ?: Intent(
Intent.ACTION_VIEW,
Uri.parse("${BASE_URL}${URLEncoder.encode(utterance, ENCODING)}")
)
The idea is that I want the bottom Intent
to be returned if either processUtterance()
returns null, resolveActivityInfo()
returns null, or activityInfo.exported
is false. I welcome comments on correctness and style.dfriehs
02/13/2020, 1:43 PMclass DelayUntilReady<T>(private val builder: () -> T) {
private companion object {
enum class State { READY, WAIT }
}
private val channel: Channel<Unit> = Channel(0)
private var state: State = State.WAIT
fun setReady() {
state = State.READY
channel.offer(Unit)
}
fun setWait() {
state = State.WAIT
}
suspend fun get(): T {
while (state == State.WAIT) channel.receive()
return builder.invoke()
}
}
object Cache {
private var elements: Map<String, String> = emptyMap()
private val elementAwait = DelayUntilReady { elements }
@Suppress("FunctionName")
suspend fun Elements(): Map<String, String> = elementAwait.get()
fun setupElements(builder: () -> Map<String, String>) {
elementAwait.setWait()
// parse
elements = builder.invoke()
elementAwait.setReady()
}
}
Did I miss something, or is there a better way to write this? Please note that i will have around 4-5 of these caches in the Cache
object, not just one as in the example.am
02/18/2020, 7:18 AMDiego Almeida de Oliveira
02/19/2020, 8:12 PM1
class Foo {
private val logger: Logger by lazy { Logger(getApplicationContext()) }
fun aFunctionCalledMultipleTimes() {
logger.doSomething()
}
}
2
class Foo {
fun aFunctionCalledMultipleTimes() {
val logger = Logger(getApplicationContext())
logger.doSomething()
}
}
Ellen Spertus
02/21/2020, 12:15 AMprivate fun createSearchIntent(mr: MatcherResult) =
mr.slots[THING_KEY]?.let { thing ->
val suffix = mr.slots[LOCATION_KEY]?.let { "in $it" } ?: ""
Intent(
Intent.ACTION_VIEW,
Uri.parse("navigation:q=$thing$suffix")
)
}
dave08
02/24/2020, 6:15 PM// 1
data class SomeResult(val typeOne: Bundle? = null, val orTypeTwo: Intent? = null)
if (typeOne == null)
doSomething(typeTwo)
else
doSomething(typeOne!!)
or:
// 2
sealed class SomeResult {
class TypeOneWrapper(val result: Bundle) : SomeResult
class TypeTwoWrapper(val result: Intent) : SomeResult
}
when (result) {
is TypeOneWrapper -> doSomething(result)
is TypeTwoWrapper -> doSomething(result)
}
The second seems cleaner, but requires funny ...Wrapper and val names (since the result type is not owned by me...), but the first is not as robust (doesn't ensure that at least one is set...).Brendan Weinstein
02/24/2020, 10:11 PMCan Orhan
02/26/2020, 2:17 PMsealed class UserInput<out T : Any> {
data class Value<T : Any>(val output: T) : UserInput<T>()
object Missing : UserInput<Nothing>()
}
The problem with it is that we can’t use Kotlin’s null-safe operators like :?
and .?
.
Do you think there is value in knowing why something is missing? If so, is it worth the loss of null-safe operators?tipsy
03/09/2020, 2:47 PMval key = myMap.filterValues { it == "value" }.keys.firstOrNull()
Ellen Spertus
03/09/2020, 5:38 PMinternal fun getString(key: String): String? {
val (tableName, fieldName) = splitDottedString(key)
return getString(tableName, fieldName)
}
Ellen Spertus
03/24/2020, 12:15 AMoverride fun toString() =
StringBuilder("MatchResult(\"").apply {
append(baseString())
append("\"")
append(slotString())
append(if (parameters.isEmpty()) "" else ", parameters: $parameters")
append(if (skippedWords == 0) "" else ", skippedWords: $skippedWords")
append(if (aliasedWords == 0) "" else ", aliasedWords: $aliasedWords")
append(intentName?.let { ", intentName: $it" } ?: "")
append(", capturedWords: $capturedWords)")
}.toString()
miqbaldc
03/24/2020, 11:27 AMsetOnClickLIstener
doesn’t works on point 1, but works in point 2,
DebouncingOnClickListener
is an interface that override View.OnClickListener#onClick(View)
to prevent spamming click
see this code below:
// 1. this doesn't works
fun View.setDebouncingOnClickListener(onSafeClick: (View) -> Unit) {
setOnClickListener(DebouncingOnClickListener {
onSafeClick(it)
})
}
// 2. this works
fun View.setDebouncingOnClickListener(onSafeClick: (View) -> Unit) {
val listener = DebouncingOnClickListener {
onSafeClick(it)
}
setOnClickListener(listener)
}
Daniel
03/25/2020, 10:15 PMfun <T> List<T>.isSameAs(other: List<T>): Boolean {
if(size != other.size) return false
forEachIndexed { index, element ->
if(element !== other[index]) return false
}
return true
}
Does anybody have an idea? Also maybe there might be a better way to check this?Cody Engel
04/03/2020, 2:30 PMsealed class Article {
abstract val title: String
abstract val body: String
abstract val updatedAt: Date
abstract val categories: List<Category>
data class New(
override val title: String,
override val body: String,
override val updatedAt: Date,
override val categories: List<Category>
) : Article()
data class Existing(
override val title: String,
override val body: String,
override val updatedAt: Date,
override val categories: List<Category>,
val id: UUID
) : Article()
}
👋🏻 I’m working on modeling the different states an object could be in (say for GET
, POST
, PUT
, and DELETE
) and I’ve landed on this for now. The New
variant would be exclusively for POST
requests while the Existing
would be used for GET
, PUT
, and DELETE
, although the delete would only require the id.
Thoughts?zmunm
04/06/2020, 5:45 AMlist.lastOrNull { it is Goods } as? Goods
Eugen Martynov
04/09/2020, 9:18 AMval check = true
when(check) {
true -> println("it's true")
false -> println("it's false")
}
Eugen Martynov
04/09/2020, 9:18 AMval check = true
when(check) {
true -> println("it's true")
false -> println("it's false")
}
Mike
04/09/2020, 11:53 AMif
is the more readable choice. When
is better for completeness check on enum/sealed class, or those cases where your if
has at least 3 branches.Eugen Martynov
04/09/2020, 12:55 PMCody Engel
04/09/2020, 1:41 PMif (check) println("it's true") else println("it's false")
daphillips
04/09/2020, 2:40 PM