https://kotlinlang.org logo
Docs
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
  • s

    smilecs

    03/02/2018, 2:02 PM
    here’s a link to the gist https://gist.github.com/smilecs/c4e5f880fb8feb30eefebf5a45714c8f
    k
    d
    • 3
    • 3
  • o

    oday

    03/06/2018, 8:01 AM
    I need a little help with this filter function https://pastebin.com/i6V7L5xq
    a
    k
    • 3
    • 42
  • b

    bjartek

    03/18/2018, 9:26 PM
    @chi just out of curiosity will deleteNode accept tailrec before fun?
    c
    • 2
    • 2
  • o

    oday

    03/20/2018, 11:10 AM
    instead of my forEach you placed a map?
    a
    • 2
    • 1
  • j

    jtravis

    04/02/2018, 9:59 PM
    One
    shouldThrow
    method takes an exception, the other takes a callback with the exception as the first arg, so I don’t understand why it wouldn’t be able to figure that out…
    a
    • 2
    • 2
  • o

    oday

    05/08/2018, 11:10 AM
    can I post code here with a bug?
    a
    • 2
    • 3
  • o

    oday

    05/08/2018, 11:12 AM
    why does line 6 get called multiple times? https://pastebin.com/tz0gkZrg many many times first when I insert 1 row and the count is 1, it gets called twice, and then after that the calls just keep increasing pastes the count 6 or 10 times
    a
    • 2
    • 7
  • h

    Hamza

    06/11/2018, 8:21 AM
    how can i make this easier for myself?
    p
    s
    o
    • 4
    • 10
  • a

    Ayden

    06/14/2018, 2:42 PM
    Would you mind to take a look one my
    SwipeRefreshLayout
    ? Am I doing something redundant?
    /*
        Fetching data from Firebase and
        passing the value to Adapter
        */
    val addValueEventListener = firebaseReference.addValueEventListener(object : ValueEventListener {
        override fun onCancelled(p0: DatabaseError) {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }
    
        override fun onDataChange(p0: DataSnapshot) {
            if (p0!!.exists()) {
                val vibeList = mutableListOf<Vibes>()
                // V stands for Vibe
                for (v in p0.children) {
                    val vibe = v.getValue(Vibes::class.java)
                    vibeList.add(vibe!!)
                }
                recyclerView.adapter = VibeAdapter(vibeList)
            }
        }
    
    })
    
    
    /*
        Fetch data from Firebase and
        passing the value to Adapter whenever
        swipe refresh triggered
        */
    swipeRefreshLayout.setOnRefreshListener {
        val addValueEventListener = firebaseReference.addValueEventListener(object : ValueEventListener {
            override fun onCancelled(p0: DatabaseError) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }
    
            override fun onDataChange(p0: DataSnapshot) {
                if (p0!!.exists()) {
                    val vibeList = mutableListOf<Vibes>()
                    // V stands for Vibe
                    for (v in p0.children) {
                        val vibe = v.getValue(Vibes::class.java)
                        vibeList.add(vibe!!)
                    }
                    recyclerView.adapter = VibeAdapter(vibeList)
                }
            }
    
        })
    }
    d
    a
    • 3
    • 4
  • s

    snowe

    06/16/2018, 4:42 PM
    var resultValidator = testExecutor.whenever(wheneverCommand!!)
            resultValidator = expects.events?.let { resultValidator.expectEvents(*it.toTypedArray()) } ?: resultValidator
            resultValidator = expects.eventsMatching?.let { resultValidator.expectEventsMatching(it) } ?: resultValidator
            resultValidator = expects.returnValue?.let { resultValidator.expectReturnValue(it) } ?: resultValidator
            resultValidator = expects.returnValueMatching?.let { resultValidator.expectReturnValueMatching(it) } ?: resultValidator
    d
    • 2
    • 14
  • h

    Hamza

    06/21/2018, 2:47 PM
    "INVALID REQUEST"                     -> html("The PayPal API failed us. INVALID_REQUEST")
          "AUTHENTICATION_FAILURE"              -> html("I'm sure we authenticated. Right, guys? AUTHENTICATION_FAILURE")
          "NOT_AUTHORIZED"                      -> html("What do you mean we are not authorized? &gt;:( NOT_AUTHORIZED")
          "RESOURCE_NOT_FOUND"                  -> html("Guys, we need to update our API. RESOURCE_NOT_FOUND")
          "METHOD_NOT_SUPPORTED"                -> html("This wasn't suppose to happen... METHOD_NOT_SUPPORTED")
          "MEDIA_TYPE_NOT_ACCEPTABLE"           -> html("This wasn't suppose to happen... MEDIA_TYPE_NOT_ACCEPTABLE")
          "UNPROCESSABLE_ENTITY"                -> html("Guys, we broke PayPal! UNPROCESSABLE_ENTITY")
          "RATE_LIMIT_REACHED"                  -> html("We've reached max capacity. Please try again later. RATE_LIMIT_REACHED")
          "INTERNAL_SERVICE_ERROR"              -> html("Look. PayPal. You need to fix your system. INTERNAL_SERVICE_ERROR")
          "SERVICE_UNAVAILABLE"                 -> html("PayPal is not available at the moment. Please try again later. SERVICE_UNAVAILABLE")
    is there a better way?
    m
    • 2
    • 2
  • i

    ianbrandt

    06/25/2018, 3:25 AM
    Been practicing with Uncle Bob's Prime Factors kata (http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata). Any improvements here, given the absence of C-style
    for
    loops in Kotlin? Perhaps a functional approach?
    fun primeFactorsOf(integer: Int): List<Int> {
    	val primeFactors = mutableListOf<Int>()
    	var n = integer
    	var divisor = 2
    	while (n > 1) {
    		while (n % divisor == 0) {
    			primeFactors.add(divisor)
    			n /= divisor
    		}
    		divisor++
    	}
    	return primeFactors
    }
    For comparison, a Java implementation with C-style loops:
    public static List<Integer> primeFactorsOf(int integer) {
    	List<Integer> primeFactors = new ArrayList<>();
    	for (int divisor = 2; integer > 1; divisor++)
    		for (; integer % divisor == 0; integer /= divisor)
    			primeFactors.add(divisor);
    	return primeFactors;
    }
    g
    d
    • 3
    • 2
  • d

    Daniel

    06/25/2018, 7:51 PM
    Suppose I want to invoke a lambda given to a mock (
    delayer
    ) then I would use (this is a question):
    argumentCaptor<() -> Unit>().apply {
                whenever(delayer.delay(capture())).thenAnswer { 
                    firstValue()
                }
            }
    ? Now suppose I only want to invoke the lambda a defined number of times because the code calles
    delay(...)
    recursively until the user stops it. How would I do this? I came up with:
    argumentCaptor<() -> Unit>().apply {
                var invocationCount = 0
    
                whenever(delayer.delay(capture())).thenAnswer {
                    if(invocationCount < times) {
                       ++invocationCount
    
                       firstValue()
                   }
               }
            }
    But that does not seem like a clean solution
    a
    s
    • 3
    • 6
  • a

    Ayden

    06/26/2018, 2:06 PM
    Is there a way to write this line of code in a better way?
    val httpLoggingInterceptor = HttpLoggingInterceptor().level = HttpLoggingInterceptor.Level.BODY
    a
    b
    c
    • 4
    • 8
  • h

    Hamza

    06/29/2018, 4:22 PM
    any suggestions on this snippet?i feel i did pretty well but there are always some tricks kotlin has up its sleeve ¯\_(ツ)_/¯
    u
    • 2
    • 1
  • h

    Hamza

    06/29/2018, 4:31 PM
    println("hello".apply {
    		replace("h", "H")
    	})
    }
    l
    a
    • 3
    • 11
  • s

    Shawn

    07/03/2018, 5:48 AM
    maybe I’m missing some context but it seems like you could at least simplify it to
    buttonRegister.isEnabled = ! (isEmpty(email) && isEmpty(password) && isEmpty(confirmPassword))
    but
    !
    is a source of contention among a lot of developers since it’s easy to miss or forget to use
    p
    a
    • 3
    • 3
  • a

    Ayden

    07/03/2018, 7:04 AM
    @Shawn may I know what is the correct or best way of doing it?
    p
    g
    +2
    • 5
    • 6
  • k

    kristofdho

    07/12/2018, 3:04 PM
    fillAdIds
    is also only used once so why define a function for it
    👍 1
    ☝️🏽 1
    a
    • 2
    • 2
  • a

    Andreas Sinz

    07/12/2018, 4:19 PM
    IMO your code is far more complex than it needs to be (e.g. temporarily storing data inside the class
    tempAdIds
    ,
    currentAdId
    , ...) which can lead to nasty race conditions/other kind of bugs later on
    a
    • 2
    • 1
  • r

    robin

    07/24/2018, 1:53 PM
    Any ideas, or does this look good enough for you? (Please disregard the fact that it doesn't use the subtraction rule to make the numerals shorter)
    DecimalToRoman_kt.kt
    • 1
    • 1
  • t

    tianhao

    07/25/2018, 6:01 AM
    Hi, guys below is my code to send a message to Kafka using Java API, I would like to do a code review and meanwhile for producer value a got a warning like
    accessing non-final property in constructor
    not sure how is the fix for that? Thanks
    class KafkaService {
    
      val producer: KafkaProducer<String, String>
    
      init {
        val props = Properties()
        props[ProducerConfig.BOOTSTRAP_SERVERS_CONFIG] = "127.0.0.1:9092"
        props[ProducerConfig.CLIENT_ID_CONFIG] = "DemoProducer"
        props[ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java.name
        props[ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java.name
    
        producer = KafkaProducer(props)
      }
    
      fun sendToKafka(topic: String, message: String) {
        val producerRecord: ProducerRecord<String?, String> = ProducerRecord(topic, null, message)
        producer.send(producerRecord)
      }
    }
    h
    • 2
    • 1
  • a

    Ayden

    07/27/2018, 9:21 AM
    Just one file.
    g
    • 2
    • 1
  • x

    x80486

    08/07/2018, 2:50 AM
    Hello folks! Is there a better way to do this?
    class Response(val message: String, val path: String) {
      val timestamp: Long = Instant.now().toEpochMilli()
    
      var status: Int = 0
    
      lateinit var error: String
    
      companion object {
        fun clientError(message: String, path: String): Response {
          return Response(message, path).apply { status = 400; error = "Bad Request" }
        }
    
        fun serverError(message: String, path: String): Response {
          return Response(message, path).apply { status = 500; error = "Internal Server Error" }
        }
      }
    }
    s
    • 2
    • 3
  • t

    twisterrob

    08/09/2018, 11:42 PM
    ?.
    vs
    if
    Which one is better in the following example and why? (open to improvements)
    s
    h
    • 3
    • 8
  • l

    louiscad

    08/11/2018, 8:46 AM
    Hi, anyone knows how I can make the following snippet more safe?
    /** Matches [android.support.v7.app.AppCompatViewInflater.createView] content. */
    val appCompatViewFactory = { clazz: Class<out View>, context: Context, _: Style<out View>? ->
        when (clazz) {
            TextView::class.java -> AppCompatTextView(context)
            Button::class.java -> AppCompatButton(context)
            ImageView::class.java -> AppCompatImageView(context)
            EditText::class.java -> AppCompatEditText(context)
            ...
            else -> null
        }
    }
    The issue is that there's no type check, I could return anything for anytype and the compiler won't fail. I want to make sure each when branch returns an object of the type of the case on which it matched.
    a
    a
    • 3
    • 18
  • k

    kotlin_questions

    08/11/2018, 4:02 PM
    But i could also do this on a Note level instead of a field level what would be a good design here?
    r
    • 2
    • 3
  • g

    griffio

    08/12/2018, 7:11 PM
    @antoin_m Yes - from my understanding it will work as expected with the type simply as the Vec sealed class. No extra casting is needed. The compiler will correctly show the “exhaustive check” if you add another data class.
    operator fun Double.times(vec: Vec) = when (vec) {
        is Vec2 -> vec.copy(this * vec.x, this * vec.y)
        is Vec3 -> vec.copy(this * vec.x, this * vec.y, this * vec.z)
    }
    a
    • 2
    • 1
  • a

    Andreas Sinz

    08/12/2018, 7:47 PM
    @antoin_m and the
    as T
    -cast is needed, because the return type of your
    when
    is
    Vec
    and not
    T
    u
    a
    • 3
    • 3
  • a

    Ayden

    08/13/2018, 7:07 AM
    Hi guys. Is there a way to make this code become shorter and efficient?
    if (TextUtils.isEmpty(name)) {
            textInputName.isErrorEnabled = true
            textInputName.error = "Name cannot be empty."
        }
        if (TextUtils.isEmpty(email)) {
            textInputEmail.isErrorEnabled = true
            textInputEmail.error = "Email cannot be empty."
        }
        if (TextUtils.isEmpty(password)) {
            textInputPassword.isErrorEnabled = true
            textInputPassword.error = "Password cannot be empty."
        }
        if (TextUtils.isEmpty(password)) {
            textInputConfirmPassword.isErrorEnabled = true
            textInputConfirmPassword.error = "Confirm password cannot be empty."
        }
        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            textInputEmail.isErrorEnabled = true
            textInputEmail.error = "Email format does not valid."
        }
        if (!(password.length >= 8)) {
            textInputPassword.isErrorEnabled = true
            textInputPassword.error = "Password length must be greater than 8 character."
        }
        if (!(confirmPassword.length >= 8)) {
            textInputConfirmPassword.isErrorEnabled = true
            textInputConfirmPassword.error = "Confirm password length must be greater than 8 character."
        }
        if (!(password.equals(confirmPassword))) {
            textInputConfirmPassword.isErrorEnabled = true
            textInputConfirmPassword.error = "Confirm Password does not match with Password"
        }
    }
    g
    • 2
    • 12
Powered by Linen
Title
a

Ayden

08/13/2018, 7:07 AM
Hi guys. Is there a way to make this code become shorter and efficient?
if (TextUtils.isEmpty(name)) {
        textInputName.isErrorEnabled = true
        textInputName.error = "Name cannot be empty."
    }
    if (TextUtils.isEmpty(email)) {
        textInputEmail.isErrorEnabled = true
        textInputEmail.error = "Email cannot be empty."
    }
    if (TextUtils.isEmpty(password)) {
        textInputPassword.isErrorEnabled = true
        textInputPassword.error = "Password cannot be empty."
    }
    if (TextUtils.isEmpty(password)) {
        textInputConfirmPassword.isErrorEnabled = true
        textInputConfirmPassword.error = "Confirm password cannot be empty."
    }
    if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
        textInputEmail.isErrorEnabled = true
        textInputEmail.error = "Email format does not valid."
    }
    if (!(password.length >= 8)) {
        textInputPassword.isErrorEnabled = true
        textInputPassword.error = "Password length must be greater than 8 character."
    }
    if (!(confirmPassword.length >= 8)) {
        textInputConfirmPassword.isErrorEnabled = true
        textInputConfirmPassword.error = "Confirm password length must be greater than 8 character."
    }
    if (!(password.equals(confirmPassword))) {
        textInputConfirmPassword.isErrorEnabled = true
        textInputConfirmPassword.error = "Confirm Password does not match with Password"
    }
}
g

gildor

08/13/2018, 7:09 AM
My suggestion Do not use TextUtils utility method
I would rewrite this completely and use some abstraction instead. Like define validator abstraction that checks passed field and return error message, than you can configure all fields with list of validators and get error without this hand-written boiler plate code and do this in much more clean and flexible way
a

Ayden

08/13/2018, 7:37 AM
@gildor would you mind to show me any sample to reference?
g

gildor

08/13/2018, 7:40 AM
Just try to abstract this behaviour
a

Ayden

08/13/2018, 7:41 AM
Okay.
@gildor is this the method I should follow? https://www.tutorialkart.com/kotlin/kotlin-abstraction/
g

gildor

08/13/2018, 8:09 AM
I’m talking about something like this: https://gist.github.com/gildor/2b2d9078253c494103e547200ecfbe59
a

Ayden

08/13/2018, 12:55 PM
@gildor I'm trying to understand your code now.
Need some time to disguise.
@gildor why you need to create
interface
first then just create
abstract
class?
Can we just create
abstract
class directly?
g

gildor

08/13/2018, 5:17 PM
Yes, you can, but interface allows you to have validator not only for single EditText field, but for anything else, for example another views or even got multiple views at the same time, or not for views at all This is just an example, main idea to abstract validators and define them instead of just copy paste the same code multiple times. Real approach highly depends on your needs and always trade off between complexity, amount of code etc Also depends on view features, for example implementation for TextInputLayout and EditText can be different I just want to show approach, where if you think about your case you often can find some way how to simplify your code and abstract inplementation from behavior
View count: 1