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
  • b

    bob

    03/06/2017, 9:11 PM
    @Andreas Sinz Okey, what would you suggest as a good workaround since I do work in a mixed java-kotlin project and have a lot of interfaces in java that I have to implement in kotlin, and this problem occurs from time to time.
    a
    • 2
    • 3
  • v

    voddan

    04/01/2017, 1:53 PM
    What's the deal with
    KFunction1<@ParameterName(name = "ctx") RoutingContext, Unit>
    ? Is it better than
    (ctx: RoutingContext) -> Unit
    ?
    j
    • 2
    • 3
  • v

    vinicius.rob.cunha

    05/05/2017, 2:16 PM
    Hello, has any way to improve this conditional?
    read.cutOn != meterCut && (meter.cutDate != null || readDate.after(meter.cutDate))
    j
    l
    e
    • 4
    • 12
  • d

    Daniel

    05/08/2017, 11:09 PM
    Suppose I want to get the lowest property of an object in an array of said objects, might there be a better way than:
    source.minBy { it.startX }?.startX ?: 0
    Maybe a way to get the value of the property directly from the collection instead the object which it belongs to?
    k
    • 2
    • 4
  • c

    cleiter

    05/09/2017, 8:38 AM
    @christophsturm something like
    val (a, b) = if (true) Pair("a", "b") else Pair(null, null)
    👍 1
    a
    • 2
    • 1
  • m

    michaelsims

    05/10/2017, 1:54 PM
    I only see
    var num
    , no
    var buf
    m
    • 2
    • 1
  • m

    michaelsims

    05/10/2017, 1:54 PM
    while (true) {
        val num = fi.read(buf).takeIf { it > 0 } ?: break
        fo.write(buf, 0, num)
    }
    👍 2
    m
    • 2
    • 1
  • p

    pguardiola

    05/28/2017, 8:12 AM
    If I define it using the concrete type
    String
    doesn’t complaint don’t know why but it works ¯\_(ツ)_/¯ thanks @anstaendig 👍
    a
    • 2
    • 9
  • t

    tipsy

    06/03/2017, 12:45 PM
    i know this is probably too much to ask, but i'm looking into porting my java-project to kotlin. i've done the port, and it seems to be working, but it would be great if someone who knows more kotlin than i do could scroll through and see if things are okay: https://github.com/tipsy/javalin/pull/11
    g
    • 2
    • 3
  • d

    dh44t

    06/03/2017, 8:11 PM
    I'll have a look, no promises
    t
    • 2
    • 3
  • j

    jlleitschuh

    06/05/2017, 9:11 PM
    If I have a kotlin interface like this:
    interface IncomingJsonMessageHandler {
        operator fun invoke(methodName: String, arg: String): String
    }
    Is this really the only good way to declare the constructor so that I can use it both for DI and as a lambda in tests is to do this goofyness:
    class IncomingRPCHandler
    @Inject constructor(
        private val connectionProvider: ConnectionProvider,
        private val incomingJsonMessageHandler: IncomingJsonMessageHandler) {
    
        internal constructor(
            connectionProvider: ConnectionProvider,
            incomingJsonMessageHandler: (String, String) -> String) :
            this(connectionProvider, object : IncomingJsonMessageHandler {
                override fun invoke(methodName: String, arg: String): String = incomingJsonMessageHandler(methodName, arg)
            })
    b
    • 2
    • 1
  • x

    x80486

    06/18/2017, 2:37 AM
    Hackers...do you have a better way to write this piece of code?
    import org.jetbrains.kotlin.com.intellij.util.TimeoutUtil
    
    val formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")
    val regex = Regex("^V\\d+__.*\\.js\$")
    File("src/main/resources/db/migration").walk()
        .filterNot { it.isDirectory or it.name.matches(regex) }
        .forEach {
          val timestamp = ZonedDateTime.now(ZoneOffset.UTC).format(formatter)
          it.renameTo(File("${it.parent}${File.separatorChar}V${timestamp}__${it.name}"))
          TimeoutUtil.sleep(100) // Wait for a moment to avoid prefix conflicts when renaming multiple files in a batch
        }
    s
    • 2
    • 2
  • t

    trubesv

    09/16/2017, 12:11 PM
    Hey guys, I'm making this really simple app in order to learn Kotlin and its best practices: https://github.com/trubesv/Kotlist Please do correct me if I'm using things wrongly, and don't hesitate to show me how to write some parts better! :kotlin:
    k
    • 2
    • 8
  • e

    Eugen Martynov

    10/10/2017, 5:53 PM
    Would you expect to find extension method in another class if you own code of the class?
    b
    • 2
    • 1
  • a

    alchzh

    11/20/2017, 2:26 PM
    Can someone review my code? Just started learning Kotlin this morning, so decided to port over some existing code... https://github.com/acz13/anagrams/tree/kotlin-rough/kotlin (x-post from #getting-started )
    d
    a
    • 3
    • 5
  • m

    menegatti

    11/21/2017, 3:13 PM
    short explanation: you map every assignee to its goal, and then you flatten that to get what you want
    e
    • 2
    • 1
  • s

    Shawn

    11/23/2017, 7:42 PM
    @ecampolo if you want your code reviewed, you gotta put up your attempt to solve the problem
    e
    • 2
    • 22
  • j

    jkbbwr

    12/15/2017, 8:11 PM
    A)
    !!
    is a code smell. B) Why crush it down further.
    e
    • 2
    • 1
  • e

    elect

    12/15/2017, 10:13 PM
    srcConnections.getOrPut(src, ::arrayListOf) += c
    d
    • 2
    • 1
  • d

    Dave Leeds

    01/09/2018, 6:50 PM
    @chi It’s a bit of a different approach, but something like this might work well:
    private enum class NestingCharacters(val open: String, val close: String) {
        BRACE("{", "}"),
        PAREN("(", ")"),
        BRACKET("[", "]");
    
        fun apply(char: String, stack: Stack<String>) {
            when (char) {
                open  -> stack.push(char)
                close -> {
                    val top = stack.peek()
                    if (stack.isStackEmpty()) throw SyntaxErrorTwoException(char)
                    if (top == open) stack.pop() else throw SyntaxErrorThreeException(top, char)
                }
            }
        }
    }
    
    fun linter2(line: String): Boolean {
        with(Stack<String>()) {
            line.split("").forEach { char ->
                NestingCharacters.values().forEach { it.apply(char, this) }
            }
            
            if (isNotEmpty()) throw SyntaxErrorOneException(peek())
        }
        return true
    }
    ✅ 2
    c
    • 2
    • 4
  • r

    roberto.guerra

    01/11/2018, 6:22 PM
    Java doesn’t support multiple inheritance
    s
    • 2
    • 1
  • s

    Shawn

    01/19/2018, 5:00 PM
    if (!existCell.isEmpty()) {
      cell = when(existCell[existCell.size - 1]) {
        1 -> 9
        3 -> 7
        7 -> 3
        9 -> 1
        else -> 0  // or some default value
      }
    }
    👍 1
    e
    • 2
    • 1
  • r

    rocketraman

    01/22/2018, 2:56 PM
    @Ayden When you have so many `if`s like that, it is often wise to consider a state machine approach instead.
    a
    • 2
    • 2
  • o

    oday

    01/23/2018, 8:13 AM
    is there a process here about how much code to show, where to show it? can it be an Android app written in Kotlin?
    a
    d
    • 3
    • 4
  • a

    Ayden

    01/23/2018, 3:25 PM
    if (
                        player1List.containsAll(listOf(1, 3, 7)) ||
                        player1List.containsAll(listOf(1, 3, 9)) ||
                        player1List.containsAll(listOf(1, 7, 9)) ||
                        player1List.containsAll(listOf(1, 3, 8))
                    ) {
                        cell = 5
                    } else if (
                        player1List.containsAll(listOf(1, 3, 4))
                    ) {
                        cell = 2
                    } else if (
                        player1List.containsAll(listOf(1, 5, 7))
                    ) {
                        cell = 3
                    } else if (
                        player1List.containsAll(listOf(1, 3, 5)) ||
                        player1List.containsAll(listOf(1, 2, 4))
                    ) {
                        cell = 7
                    } else if (player1List.containsAll(listOf(3, 5, 9))) {
                        cell = 1
                    }
    a
    l
    +4
    • 7
    • 35
  • d

    dave08

    01/29/2018, 3:20 AM
    It might also be easier on people to spot better shorcuts for you...
    d
    • 2
    • 3
  • j

    Joe

    02/02/2018, 12:53 PM
    That’s right. I keep forgetting that
    let
    actually returns something.
    a
    • 2
    • 1
  • u

    uhe

    02/02/2018, 3:03 PM
    imo the
    if else
    is more readable
    ➕ 14
    a
    d
    • 3
    • 2
  • m

    marcinmoskala

    02/10/2018, 5:38 AM
    I would like to know your opinion. I had following function:
    subscriptions += repository.getQuests()
            .applySchedulers()
            .smartSubscribe(
                    onSuccess = view::showList and this::updateUpTrackingList,
                    onError = view::handleError,
                    onFinish = view::hideLoader
            )
    Which is, as you can guess, RxJava usage. On success I use both show list on view instance (this is in presenter) and I update tracking list:
    private fun updateUpTrackingList(quests: List<Quest>) {
        AppDatabase.addAppsToInstall(*quests.map { it.pkg }.toTypedArray())
    }
    and
    is obviously commonly used function in my projects:
    infix fun <T> ((T) -> Unit).and(f: (T) -> Unit): (T) -> Unit = { this(it); f(it) }
    I had to add buffering, but I wanted to keep nice descriptive form of functions passing. So I made following function:
    private var previousList: List<Quest>? = null
    
    private fun ifChanged(onListChanged: (List<Quest>) -> Unit) = fun(list: List<Quest>) {
        if(previousList != list) {
            previousList = list
            onListChanged(list)
        }
    }
    And I use it this way:
    subscriptions += repository.getQuests()
            .applySchedulers()
            .smartSubscribe(
                    onSuccess = ifChanged(view::showList and this::updateUpTrackingList),
                    onError = view::handleError,
                    onFinish = view::hideLoader
            )
    For me it looks great but I am not sure if it is not too complex for other people. What do you think? @mg6maciej? Functional programming passionates? Everyone? PS. If I would have function delegate then I could even extract this buffering as a common patter (my proposition for this functionality is waiting on KEEP)
    d
    • 2
    • 7
  • e

    elect

    02/14/2018, 10:24 AM
    any better alternative to this?
    var navEarliestChild = g.navWindow!!
                while (navEarliestChild.parentWindow != null && navEarliestChild.parentWindow!!.flags has Wf.ChildMenu)
                    navEarliestChild = navEarliestChild.parentWindow!!
    a
    m
    • 3
    • 6
Powered by Linen
Title
e

elect

02/14/2018, 10:24 AM
any better alternative to this?
var navEarliestChild = g.navWindow!!
            while (navEarliestChild.parentWindow != null && navEarliestChild.parentWindow!!.flags has Wf.ChildMenu)
                navEarliestChild = navEarliestChild.parentWindow!!
a

Andreas Sinz

02/14/2018, 10:44 AM
@elect use recursion
e

elect

02/14/2018, 11:31 AM
uhm, smells overkill
but I'll give it a try
a

Andreas Sinz

02/14/2018, 11:37 AM
https://kotlinlang.org/docs/reference/functions.html#tail-recursive-functions
e

elect

02/14/2018, 3:39 PM
cool, I didnt know it, thanks!
m

Max Russek

02/14/2018, 10:06 PM
Also I have hunch that
generateSequence
might help https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/generate-sequence.html
View count: 2