jishindev
07/01/2019, 11:44 AMfun String.()
for each lamda inside this map creation? mapOf<String, String.() -> Unit>(
"One" to fun String.(){ println(this) }
)
It gives Type inference failed. Expected type mismatch: inferred type is Pair<String, () -> Unit> but Pair<String, String.() -> Unit> was expected
if I don't use the fun String.()
while defining the lambda.myanmarking
07/10/2019, 10:53 AM/**
* Returns a new list of size [capacity] with elements from the original list, filled with [element] if needed
*/
fun <E> List<E>.fillWith(capacity: Int, element: E?): List<E?> {
val outList = mutableListOf<E?>()
repeat(capacity){ outList.add(element) }
if(this.isEmpty()) return outList
val sl = this.subList(0, min(capacity, this.size))
sl.forEachIndexed { index, e ->
outList[index] = e
}
return outList
}
twisterrob
07/21/2019, 1:26 PMprivate fun findTheField(fields: List<Field>): Field? {
if (fields.isEmpty()) {
return null
}
if (fields.size == 1) {
return fields.first()
}
val selectedFields = fields.filter(::someCondition)
if (selectedFields.size == 1) {
return selectedFields[0]
} else {
throw IllegalArgumentException(
"Too many fields matching some condition found: ${fields.joinToString(", ")}"
)
}
}
this question was triggered by Detekt: ReturnCount
"... has 3 return statements which exceeds the limit of 2", which kind of has a point there.Harun
07/24/2019, 12:04 PMivano
07/25/2019, 11:38 AMoverride fun getItemViewType(position: Int): Int {
return if (hasHeader) {
if (position == 0) HEADER
else entryItem(position)
} else if (position == 0) ITEM_WITH_DATE else entryItem(position + 1)
}
Tobi
07/26/2019, 1:58 PMNetworkInfo#isConnectedOrConnecting
and ConnectivityManager.CONNECTIVITY_ACTION
in API 28 I wrote the following class.
https://developer.android.com/reference/android/net/NetworkInfo#isConnectedOrConnecting()
https://developer.android.com/reference/android/net/ConnectivityManager#CONNECTIVITY_ACTION
/**
* Observes network connectivity by consulting the [ConnectivityManager].
* Observing can run infinitely or automatically be stopped after the first response is received.
*/
class ConnectivityObserver @JvmOverloads constructor(
val context: Context,
val onConnectionAvailable: () -> Unit,
val onConnectionLost: () -> Unit = {},
val shouldStopAfterFirstResponse: Boolean = false
) {
private val connectivityManager
get() = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
@Suppress("DEPRECATION")
private val intentFilter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
private val broadCastReceiver = object : BroadcastReceiver() {
@Suppress("DEPRECATION")
override fun onReceive(context: Context?, intent: Intent?) {
if (ConnectivityManager.CONNECTIVITY_ACTION != intent?.action) {
return
}
val networkInfo = connectivityManager.activeNetworkInfo
if (networkInfo != null && networkInfo.isConnectedOrConnecting) {
onConnectionAvailable.invoke()
} else {
onConnectionLost.invoke()
}
if (shouldStopAfterFirstResponse) {
stop()
}
}
}
private lateinit var networkCallback: ConnectivityManager.NetworkCallback
init {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
onConnectionAvailable.invoke()
if (shouldStopAfterFirstResponse) {
stop()
}
}
override fun onLost(network: Network?) {
super.onLost(network)
onConnectionLost.invoke()
if (shouldStopAfterFirstResponse) {
stop()
}
}
}
}
}
fun start() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
// Decouple from component lifecycle, use application context.
// See: <https://developer.android.com/reference/android/content/Context.html#getApplicationContext()>
context.applicationContext.registerReceiver(broadCastReceiver, intentFilter)
} else {
connectivityManager.registerDefaultNetworkCallback(networkCallback)
}
}
fun stop() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
context.applicationContext.unregisterReceiver(broadCastReceiver)
} else {
connectivityManager.unregisterNetworkCallback(networkCallback)
}
}
}
It can be used this way:
val onConnectionAvailable = TODO()
val connectivityObserver = ConnectivityObserver(context, onConnectionAvailable)
connectivityObserver.start()
connectivityObserver.stop()
or this way:
val onConnectionAvailable = TODO()
val onConnectionLost = TODO()
ConnectivityObserver(context,
onConnectionAvailable,
onConnectionLost,
shouldStopAfterFirstResponse = true
).start()
What do you think about my implementation?corneil
08/02/2019, 10:02 PMghosalmartin
08/09/2019, 1:17 PM@Before
I've been initing my tests as such. Since the subject is inited with mocks and their values are whats important not whats being injected. Can the @Before be foregoed? Or is there anyway I can have an @Before
work on a variable since I don't want to lateinit
the subjectlouiscad
08/16/2019, 4:28 PMsuspend fun awaitSubmissionOfPhoneNumberInput(): String
1️⃣ : suspend fun awaitPhoneNumberInputSubmission(): String
ursus
08/25/2019, 12:00 AMmiqbaldc
08/26/2019, 11:03 AMsource
& destination
. is it the right way to do this?
Currently, I'm checking the list of contents is DataA return ResultA
or DataB return ResultB
. But here's my actual usecase:
typealias ListMovieEntity = List<MovieEntity>
typealias ListMovieResponse = List<MovieResponse>
class MovieEntityMapper {
companion object {
fun <S : Any, D : Any> from(movies: ListMovie<S>): List<D> = movies.map {
with(it) {
when (this) {
is MovieEntity -> Movie(id)
is MovieResponse -> MovieEntity(id)
else -> TODO()
} as D
}
}
}
}
I'm doing this because, I can't do the overload on both kotlin / java due to type erasure in the runtime. e.g:
fun fun1(list: List<A>)
fun fun2(list: List<B>)
// this two function will clashes each other.
elect
08/27/2019, 12:08 PMvar validated = true
if (validated)
validated = initProgram()
if (validated)
validated = initBuffer()
return validated
With the kotlin Result
or something more functional oriented?Milan Hruban
08/31/2019, 8:42 AMpublic static ScoreDto score(String email, String name, String surname, Function<String, Boolean> function)
What would be the idiomatic/more readable approach to call it from Kotlin, given that dataProvider
is a nullable instance of class that implements Function<String, Boolean>?
score(
"<mailto:some_email@domain.com|some_email@domain.com>",
"John",
"Doe"
) { dataProvider?.apply(it) }
vs
score(
"<mailto:some_email@domain.com|some_email@domain.com>",
"John",
"Doe",
{ dataProvider?.apply(it) }
)
vs
dataProvider?.let {
score(
"<mailto:some_email@domain.com|some_email@domain.com>"
"John",
"Doe",
it
)
}
skendrick
10/03/2019, 2:55 PMsomeLetter
··A··
·B·B·
C···C
·B·B·
··A··
The problem description & the solution: https://gist.github.com/adnauseum/4a7c9762d57f3b82b1dd18b1204af3cb
If you want to review it, 1) thanks, 2) leave a comment in a thread or on the gist—whatever is easiest for you. 🙇 THANK YOU! Actually, the fact that anybody would leave a comment is mind-blowing, so thanks for even reading and putting in the effort!Mohamed Ibrahim
10/17/2019, 7:59 AMfun <R> Observable<R>.checkInternetConnection(): Observable<R> {
return if (NetworkUtils.isConnected) this else Observable.error(NoInternetException)
}
Mohamed Ibrahim
10/17/2019, 8:00 AMfun <R> Observable<R>.mapErrors(): Observable<R> {
return this.onErrorResumeNext { t: Throwable ->
val error = when (t) {
is UnknownHostException -> NoInternetException
else -> t
}
Observable.error(error)
}
}
Eugen Martynov
10/23/2019, 7:45 AMAyden
10/27/2019, 5:01 AMfindViewById<Button>(R.id.test).setOnClickListener(View.OnClickListener {
if (progressBar.visibility == View.VISIBLE) {
showProgressBar(false)
} else {
showProgressBar(true)
}
})
fun showProgressBar(visibility: Boolean) {
progressBar.visibility = if (visibility) {
View.INVISIBLE
} else {
View.VISIBLE
}
}
Brian Carbone
10/28/2019, 2:53 PMval Array<Coordinate>.centroid
get() = fold(mutableMapOf<Double, Double>()) { acc, coord -> acc.also { it[coord.x] = coord.y } }.run {
Coordinate(keys.average(), values.average())
}
Is there a better way to get the average coordinate from an array of coordinates? (Coordinate is a simple data class holding two doubles, x and y)tipsy
10/31/2019, 6:19 PMprivate fun changeListener(obj: Any) {
fun getObjectString(): String {
val baos = ByteArrayOutputStream()
ObjectOutputStream(baos).also { it.writeObject(obj) }.also { it.close() }
return baos.toString()
}
var oldValue = getObjectString()
Thread {
while (true) {
val newValue = getObjectString()
if (oldValue != newValue) {
println("Change detected")
oldValue = newValue
}
Thread.sleep(250)
}
}.start()
}
Daniel
11/10/2019, 10:44 AMval elementChanges = listOf("a", "b", "b").zipWithNext { a, b ->
if(b != a) 1 else 0
}.sum()
I try to get the count of "changes" in a list in relation to one element to the next:
Here for example I see that there is a change from "a" to "b", but after that there are no changes anymore "b" to "b"Gerard Klijs
12/02/2019, 7:42 AMEugen Martynov
12/02/2019, 3:38 PMeditText.length() in 2 until maxEditLength
?momrak
12/02/2019, 4:20 PM@GetMapping(value = ["download-all"], produces = ["application/zip"])
fun downloadAll(): ByteArray {
val outputStream = ByteArrayOutputStream(1024)
val bufferedOutputStream = BufferedOutputStream(outputStream)
val zipOutputStream = ZipOutputStream(bufferedOutputStream)
val docIds = docService.getDocIds()
runBlocking {
val docStream = docIds
.map { GlobalScope.async { docService.getDoc(it) } }
.map { ByteArrayInputStream(it.await()) }
.map { BufferedInputStream(it) }
docStream.forEachIndexed { index, bufferedInputStream ->
val zipEntry = ZipEntry("test${index}.pdf")
zipOutputStream.putNextEntry(zipEntry)
bufferedInputStream.copyTo(zipOutputStream, 1024)
bufferedInputStream.close()
zipOutputStream.closeEntry()
}
zipOutputStream.close()
}
return outputStream.toByteArray()
}
Brian Carbone
12/04/2019, 6:54 PMDiego Almeida de Oliveira
12/05/2019, 8:50 PMfun String.Companion.joinIfNotNullOrBlank(vararg params: String?, separator: String = ", "): String =
params.filter { !it.isNullOrBlank() }.joinToString(separator)
Brian Carbone
12/06/2019, 6:08 PMTuang
12/23/2019, 9:46 PMval carMst: List<(Mutable)Map<String!, Any!>!>!
val carUserIds: List<(Mutable)Map<String!, Any!>!>!
....
....
val result = ArrayList<Car>()
for (mst in carMst) {
val userIds = ArrayList<Int>()
for (uids in carUserIds) {
if (mst["car_id"] == uids["car_id"]) {
userIds.add(uids["user_id"] as Int)
}
}
val car = Car(
mst["car_id"] as Int,
mst["model"] as String,
userIds
)
result.add(car)
}
i dont know too much about collection and lambda but with collection this can be more simple and beautiful right? 😀
thankscsturtevant
12/30/2019, 10:55 PMType mismatch: inferred type is (Mutable)List<Task!>? but MutableList<Task> was expected
I’m writing a Kotlin class implementing this interface method:
List<Task> getTasksReport(@NonNull String filter);
The Kotlin implementation is:
override fun getTasksReport(filter: String): MutableList<Task> {
val response = todoistRestClient.getTasks(TODAY_FILTER)
val tasks = response.body
println(tasks)
return tasks
}
Would changing the Kotlin by adding the cast to the return to the following be the best implementation?:
override fun getTasksReport(filter: String): MutableList<Task> {
val response = todoistRestClient.getTasks(TODAY_FILTER)
val tasks = response.body
println(tasks)
return tasks as MutableList<Task>
}
aoriani
12/31/2019, 12:36 AMaoriani
12/31/2019, 12:36 AMcsturtevant
12/31/2019, 5:29 AMresponse
is a
org.springframework.http.ResponseEntity<List<Task>>
with Task
being a regular POJO. val tasks = response.body ?: arrayListOf<Task>()
does look better but if you have any other suggestions based on the new evidence I’d be highly appreciative!aoriani
12/31/2019, 9:00 AM@Nullable
so Kotlin can at least say it returns a nullable type. Thus coercing to a non-null could be a problem.
Now the best code actually depends of the context. I am not familiar with Spring.getBody()
is nullable because ResponseEntity
represents any HTTP response and not all responses have a body. An HTTP 204, for instance, doesn't have a body.