https://kotlinlang.org logo
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
codereview
  • j

    jishindev

    07/01/2019, 11:44 AM
    Any way to simplify this by getting rid of
    fun 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.
    s
    • 2
    • 3
  • m

    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
    }
    w
    d
    • 3
    • 5
  • t

    twisterrob

    07/21/2019, 1:26 PM
    I have a function as shown below, I'm wondering if there's a better way to express this (focusing on `if`/`else`/`return`/`throw` structure):
    private 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.
    d
    e
    • 3
    • 8
  • h

    Harun

    07/24/2019, 12:04 PM
    Any ideas to make this code more idiomatic?
    Untitled.kt
    b
    • 2
    • 5
  • i

    ivano

    07/25/2019, 11:38 AM
    override 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)
        }
    m
    • 2
    • 3
  • t

    Tobi

    07/26/2019, 1:58 PM
    In order to address the deprecation of
    NetworkInfo#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?
    m
    d
    • 3
    • 15
  • c

    corneil

    08/02/2019, 10:02 PM
    Is this ridiculous or useful?
    if-apply.kt
    👎 1
    d
    t
    r
    • 4
    • 7
  • g

    ghosalmartin

    08/09/2019, 1:17 PM
    Instead of a
    @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 subject
    Untitled
    g
    c
    • 3
    • 7
  • l

    louiscad

    08/16/2019, 4:28 PM
    Which one do you prefer? Feel free to tell why in the thread if you have explainable reasons. 0️⃣ :
    suspend fun awaitSubmissionOfPhoneNumberInput(): String
    1️⃣ :
    suspend fun awaitPhoneNumberInputSubmission(): String
    0️⃣ 1
    1️⃣ 15
    d
    m
    • 3
    • 3
  • u

    ursus

    08/25/2019, 12:00 AM
    what Im kind of uneasy is the RequestPin and Ok substate is duplicated everywhere, its essentially the same thing, but it matters in which mode (parent) its in, so, is the way I sliced the states correct?
    b
    • 2
    • 1
  • m

    miqbaldc

    08/26/2019, 11:03 AM
    Actually I need to detect 2 generic classes.
    source
    &
    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.
    t
    s
    • 3
    • 4
  • e

    elect

    08/27/2019, 12:08 PM
    would it be possible/make sense substitute constructs like this:
    var validated = true
    
            if (validated)
                validated = initProgram()
            if (validated)
                validated = initBuffer()
    
            return validated
    With the kotlin
    Result
    or something more functional oriented?
    s
    r
    j
    • 4
    • 5
  • m

    Milan Hruban

    08/31/2019, 8:42 AM
    Hello, I have a java function with following signature:
    public 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
        )
    }
    s
    m
    • 3
    • 3
  • s

    skendrick

    10/03/2019, 2:55 PM
    Hi 😄, Here’s a programming puzzle I solved with Kotlin. Please pick it apart, if ya like! I’ve been doing Kotlin for like 5 days. But also lemme know if the approach was off or unclear! tldr problem description: print a diamond start from A to
    someLetter
    ··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!
    👍 3
    t
    b
    • 3
    • 10
  • m

    Mohamed Ibrahim

    10/17/2019, 7:59 AM
    What do you think about those ext function
    fun <R> Observable<R>.checkInternetConnection(): Observable<R> {
    return if (NetworkUtils.isConnected) this else Observable.error(NoInternetException)
    }
    r
    b
    • 3
    • 2
  • m

    Mohamed Ibrahim

    10/17/2019, 8:00 AM
    fun <R> Observable<R>.mapErrors(): Observable<R> {
    return this.onErrorResumeNext { t: Throwable ->
    val error = when (t) {
    is UnknownHostException -> NoInternetException
    else -> t
    }
    Observable.error(error)
    }
    }
    f
    • 2
    • 3
  • e

    Eugen Martynov

    10/23/2019, 7:45 AM
    When I do specific class I would like to have better names for the params, since I know the context
    w
    k
    • 3
    • 5
  • a

    Ayden

    10/27/2019, 5:01 AM
    Hi guys. I have two functions here, not sure if it can be more simplify.
    findViewById<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
        }
    }
    k
    r
    +2
    • 5
    • 6
  • b

    Brian Carbone

    10/28/2019, 2:53 PM
    val 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)
    d
    • 2
    • 6
  • t

    tipsy

    10/31/2019, 6:19 PM
    i have a stupid problem. i need to detect changes to an object which i do not own. my code looks like this:
    private 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()
    }
    f
    d
    • 3
    • 3
  • d

    Daniel

    11/10/2019, 10:44 AM
    Might there be a better way to achieve this?
    val 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"
    p
    m
    • 3
    • 4
  • g

    Gerard Klijs

    12/02/2019, 7:42 AM
    I would appreciate it very much if someone could take a look at https://github.com/openweb-nl/kafka-graphql-examples/tree/ge-kotlin/GraphQL-endpoint I don't do that much with kotlin yet. It's currently working, but the performance of the subscription is a lot less then the Clojure and Java implementation. So I suspect I did something stupid somewhere.
    j
    • 2
    • 2
  • e

    Eugen Martynov

    12/02/2019, 3:38 PM
    Is there more idiomatic way to write
    editText.length() in 2 until maxEditLength
    ?
    b
    a
    • 3
    • 4
  • m

    momrak

    12/02/2019, 4:20 PM
    Hi guys. This is my first time playing with coroutines and my use case is the following: I want to have an endpoint that returns a users documents as a zip of PDFs. So first I fetch all document IDs, then I want to run a coroutine to fetch each document by ID. I have a working implementation (snippet below), but I feel that there should be a more idiomatic way of doing this. Does anyone have any thoughts? Not sure if this post is best suited here or in the #coroutines channel, but I'll give it a go here! Any input is much appreciated.
    @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()
        }
    d
    • 2
    • 2
  • b

    Brian Carbone

    12/04/2019, 6:54 PM
    by adjusting the range
    b
    • 2
    • 2
  • d

    Diego Almeida de Oliveira

    12/05/2019, 8:50 PM
    How would you guys make a list of string be joined but with the condition that if a String is null or blank it won't be included in the resulting string? Is there a function that does it? I couldn't find such function so I created this extension
    fun String.Companion.joinIfNotNullOrBlank(vararg params: String?, separator: String = ", "): String =
        params.filter { !it.isNullOrBlank() }.joinToString(separator)
    l
    • 2
    • 1
  • b

    Brian Carbone

    12/06/2019, 6:08 PM
    gets you the value of key3 which is in a nested map (jackson objectmapper prerequisite not included)
    k
    • 2
    • 7
  • t

    Tuang

    12/23/2019, 9:46 PM
    i need review for my code
    val 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? 😀 thanks
    s
    • 2
    • 7
  • c

    csturtevant

    12/30/2019, 10:55 PM
    Hi there, can anyone help me resolve this Intellij warning?
    Type 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>
        }
    m
    • 2
    • 1
  • a

    aoriani

    12/31/2019, 12:36 AM
    If that "error handling strategy" is okay for you.
    c
    • 2
    • 4
Powered by Linen
Title
a

aoriani

12/31/2019, 12:36 AM
If that "error handling strategy" is okay for you.
c

csturtevant

12/31/2019, 5:29 AM
I am using OkHTTP, the
response
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!
a

aoriani

12/31/2019, 9:00 AM
Okay, so it is actually https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/HttpEntity.html#getBody-- which is also annotated with
@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.
I imagine that
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.
In your case what would missing body mean? That there're no `Task`s ? That there is an error ? You are not checking whether the request actually succeeds (if at least the response has a 200 status code). So assuming it will always succeed is in itself a problem. In both cases, would it be okay to return an empty list ? Or it is better to throw an exception to know straight away that something went wrong?
👍 1
View count: 2