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
announcements
  • d

    darkmoon_uk

    11/22/2019, 1:27 AM
    Unfortunately the experimental Java-to-Kotlin converter is outputting 'garbage' results for me: • Nested comment blocks are being left un-matched resulting in half the output being 'commented out' • Confused output for properties e.g.
    override var customText6: String? = null public get() {
        return field
      }
    ...is this ☝️ backed by a variable or computed? 🤦
    g
    a
    • 3
    • 2
  • m

    Mike

    11/22/2019, 2:04 AM
    Is there a way to get an invite to the iOS channel?
    j
    b
    +2
    • 5
    • 11
  • d

    df

    11/22/2019, 9:50 AM
    why is not not allowed to combine lateinit with custom setters?
    i
    • 2
    • 3
  • a

    Adriano Celentano

    11/22/2019, 10:47 AM
    As there are so many ressources about domain modeling these days, i had today a use Case where i thought it would make sense. I want to validate a Document and return a type ValidatedDocument Then i want to upload and only accept the type ValidatedDocument for it But my Problem is that ValidatedDocument can not only be created from my validation method but also just by calling the constructor. Is there sth obvious i am missing ?
    data class Document(val uri: Uri)
    
    data class ValidatedDocument(val uri: Uri)
    
    fun validateDocument(document: Document): ValidatedDocument {
        val valid = true
        if(valid) {
            return ValidatedDocument(documentUpload.uri)
        } else {
            throw IllegalArgumentException("not valid")
        }
    }
    
    fun uploadDocument(validatedDocument: ValidatedDocument) {
    
    }
    
    fun main() {
        val doc = Document(uri = Uri.EMPTY)
    
        val validDoc = validateDocument(doc)
    
        uploadDocument(validDoc)
    }
    m
    u
    • 3
    • 5
  • r

    Robert Jaros

    11/22/2019, 11:29 AM
    How to create a single parameter function that can take both
    String
    or
    String?
    as a parameter and returns simple
    String
    when called with
    String
    or nullable
    String?
    when called with
    String?
    ?
    d
    • 2
    • 20
  • y

    Yekta

    11/22/2019, 12:11 PM
    What is the error in here?
    s
    • 2
    • 1
  • y

    Yekta

    11/22/2019, 12:12 PM
    Any solutions?
    d
    • 2
    • 3
  • d

    Daniele Segato

    11/22/2019, 12:32 PM
    A bit of a language question:
    data class
    can't be extended (ok). If I chose to use an
    interface
    and implement it with a
    data class
    I can do things like this
    interface MyPublicInterface {
      val x: String
      val y: Int
      val z: Whatever
    }
    
    data class MyImplementation(
      override val x: String,
      override val y: Int,
      override val z: Whatever
    ): MyPublicInterface
    now this is ok, but if I do this then I can't use the useful
    copy()
    or
    componentN()
    functions method that comes along with a data class on my interface without casting it to my implementation. Is there some way to make my interface declare the
    copy()
    and
    componentN()
    ? for the
    componentN()
    I guess it's possible by just defining the operators, but then I'd had to manually maintain them, still ok. But for
    copy()
    I've no idea how to do it
    l
    s
    • 3
    • 7
  • e

    elect

    11/22/2019, 1:05 PM
    isnt possible to
    @JvmName
    a custom getter extender? (
    val Bar.foo get() =..
    )
    d
    • 2
    • 2
  • s

    Sam Garfinkel

    11/22/2019, 6:44 PM
    Is there anyway to ensure a common indent for interpolated multi-line strings? Here’s an example:
    val inner = """
        - List Entry 1
        - List Entry 2
    """.trimIndent()
    
    val outer = """
    Outer:
        $inner
    """.trimIndent()
    
    fun main() {
        println(outer)
    }
    What I get:
    Outer:
        - List Entry 1
    - List Entry 2
    What I want (expect):
    Outer:
        - List Entry 1
        - List Entry 2
    c
    s
    • 3
    • 5
  • i

    igor.wojda

    11/22/2019, 9:47 PM
    I am using a lof of Kotlin (for Android apps) and I would like to build some server-side apps. What would be your recommendation for server-side platform/frameworks/tools, ideally Kotlin based or at least tech something that it’s quite to switch from Kotlin (I am total noob here).
    m
    j
    +3
    • 6
    • 10
  • c

    Cyberpunk Keanu

    11/23/2019, 1:40 PM
    Anyone knows which font is used in the Kotlin logo? I thought it would be Helvetica, but as you can see the o is slightly off here
    🌶️ 1
    k
    • 2
    • 4
  • m

    mending3

    11/23/2019, 3:59 PM
    how do I write two dimensional array in kotlin? in php we can write it very easily, such as
    $arr = [
        [
            "name" => "john"
        ],
        [
            "name" => "michael"
        ]
    ];
    how do I achieve the above?
    m
    s
    m
    • 4
    • 12
  • f

    farzad

    11/24/2019, 8:23 AM
    I have a class with some nullable properties
    data class RequestModel(
        val description: String?
    )
    and a validation function
    fun validate(model: RequestModel): RequestModel{
        if(model.description == null) throw IllegalArgumentException("description must be non null")
        return model
    }
    After this validation step, I need a way to indicate non-nullability of
    description
    property. One solution is to create a new data class which has non null propertis
    data class RequestModel(val description: String)
    . But I'm looking for a generic way to avoid creating new classes per use case. Ideal generic solution:
    fun validate(model: RequestModel): NoNullableField<RequestModel>
    How can I remove nullability from properties of a c.lass with nullable properties in a generic way? Is it usefull to use some kind of kotlin compiler contract? Link to SO question: https://stackoverflow.com/questions/59015821
    a
    • 2
    • 2
  • m

    Madalin Valceleanu

    11/24/2019, 11:23 AM
    Has anyone else has check the problem of data binding in unit tests: https://issuetracker.google.com/issues/117145132
    • 1
    • 1
  • r

    robstoll

    11/24/2019, 1:22 PM
    what is the reason that kotlin does not allow
    /
    in a function name? e.g. `fun `/`` is not allowed but `fun `+`` is
    ➕ 3
    m
    • 2
    • 1
  • a

    Anthony Styzhin

    11/24/2019, 5:33 PM
    Could someone please explain what it the key difference between these two options of the same function?
    fun findShort(s: String): Int = s.split(" ").minBy { it.length }!!.count()
    vs
    fun findShort(s: String): Int = s.split(" ").minBy { it.length }!!.length
    Both options work, pass unit tests and both are presented among solutions at codewars. Just trying to satisfy my curiosity ^^ Thanks in advance!
    k
    b
    j
    • 4
    • 9
  • k

    karelpeeters

    11/24/2019, 6:21 PM
    Is there any way to call
    bar
    here?
    inline fun <reified A: Any?> foo() {
        bar(A::class)
    }
    
    fun <B: Any> bar(cls: KClass<B>) {}
    This should be possible,
    A::class
    always returns the proper class, even if
    A
    is nullable. It looks like the compiler doesn't realize that (I'll probably report this on youtrack). Usually I'd just cast something but I'm not sure how to do that here, I want to cast to
    A!!
    but that's not real syntax of course. Any tricks?
    a
    k
    • 3
    • 4
  • n

    Nimelrian

    11/25/2019, 10:11 AM
    Hey folks, I have a small issue with sequences. I have a CSV file parser which parses rows in batches. For each batch, it updates an input set object which contains information about the batching progress (failed rows, completed rows) and stores the updated input set and the parsed objects in our database. Here's the current code:
    val inputSet = createInputSet(path, month, year, currentTimestamp)
    
    val parser = BatchingDeclineRateFileParser(batchingConfiguration.batchSize, path)
    
    return generateSequence { parser.parseBatch() }
            .map { batch ->
                val updatedInputSet = updateBatchedInputSet(inputSet, batch)
    
                transactionManager.runInTransaction {
                    rateInputRepository.createAll(batch.batchItems, month, year, updatedInputSet.id)
                    inputSetRepository.updateBatchStep(updatedInputSet)
                }
                updatedInputSet
            }
            .find { it.isProcessingDone } ?: throw JobException("Batch did not complete for some reason")
    This works in general, but due to using map I only update the original input set each time. Is there a function on
    Sequence
    which works like e.g. ReactiveX's
    scan
    where I can fold the incoming values into an accumulator? http://reactivex.io/documentation/operators/scan.html
    g
    m
    k
    • 4
    • 10
  • r

    rikusen0335

    11/25/2019, 10:38 AM
    Hello, I'm new to Kotlin, and I want to use Exposed with it, but I'm getting
    java.lang.NoClassDefFoundError: org/jetbrains/exposed/sql/Database
    .
    Does anyone know how this happen and a solution for this? Thanks.
    a
    • 2
    • 2
  • s

    Stephan Schroeder

    11/25/2019, 11:10 AM
    Does anybody know if Contracts (https://kotlinlang.org/docs/reference/whatsnew13.html#contracts) are close to leaving experimental (and if/how the final form is different from the 1.3 version)? I played around with the current version and immidiately have a feature request 😆 In Example 1 of the Contracts Proposal (https://github.com/Kotlin/KEEP/blob/master/proposals/kotlin-contracts.md#examples) they show a Smart Cast use case:
    [Returns(true) -> x is String]
    fun isString(x: Any?): Boolean = x is String
    so I was interested in seeing if I can write a reified generic version (https://pl.kotl.in/XNSuwtkvC, which would be pretty useful for custom equals-methods):
    inline fun <reified T:Any> T.hasSameClass(other: Any?): Boolean {
        contract {
            returns(true) implies (other is T)
        }
        if (this === other) return true
        return other!=null && this.javaClass == other.javaClass
    }
    Unfortunately currently this fails due to “references to type parameters are forbidden in contracts”. References to reified type parameters should be doable (<- my feature request).
    k
    • 2
    • 8
  • y

    yayabobi

    11/25/2019, 12:51 PM
    https://blog.codota.com/20-kotlin-interview-questions-for-junior-and-senior-developers/
    🙄 1
    👍 1
    k
    s
    • 3
    • 2
  • t

    tapchicoma

    11/25/2019, 8:36 PM
    seems https://github.com/JetBrains/kotlin/blob/master/ChangeLog.md hasn't been updated for Kotlin 1.3.60 release
    j
    • 2
    • 1
  • p

    pablofloresarg

    11/25/2019, 9:01 PM
    Hi guys, I have a problem with this code, I'm returning from repository a Flow<ListHouse>, the list has the house name and I want to filter it by a house name string that I have in my class. In my head filter is returning a new list with just one House so in map I am using first and get values (house values from potter api). But I always get all list house from filter so my first() in map always give me the values of the first house. I don't know why filter is not working with any(), they both are returning boolean from predicate (or at least I think so)
    Untitled
    d
    • 2
    • 3
  • j

    james

    11/26/2019, 12:31 AM
    I'm looking for some guidance around boolean naming conventions in Kotlin. I'm working with an older java class which is populated from an API, where the API returns something like
    canEditProfile
    and the java class has a field named
    isCanEditProfile
    . I'll have a new kotlin class which exposes a few of these fields, and I think the name
    isCanEditProfile
    seems a bit odd, so I'm looking for alternatives for this and a few other similar booleans. I know
    is*
    and
    has*
    are commonly accepted boolean prefixes in the java/kotlin world, I'm just wondering if
    can*
    is also acceptable in this context?
    r
    a
    • 3
    • 5
  • j

    Joey

    11/26/2019, 3:01 AM
    Can i have your opinion regarding monitoring/listening location from android and iOS device and using the common to send the data to the server. (This is an MPP/shared library project). Im having a hard time since we dont have plugins or libraries that handles location from multiplatform project. Thanks!
    d
    • 2
    • 6
  • c

    Can

    11/26/2019, 9:51 AM
    I am having severe issues with custom lint checks. Performing
    ./gradlew clean lintDebug
    sometimes include my custom checks and sometimes they do not. Same with Android Studio (inspections in the file are sometimes visible, sometimes they are not). I am having these issues in a rather large project - the same problems are not visible in an equivalent test-project. What should be the steps to see custom lint rules in action? Should just performing
    ./gradlew clean lintDebug
    lead to the result we wish?
    m
    • 2
    • 2
  • g

    Gyuhyeon

    11/26/2019, 9:53 AM
    I'm still confused about what the "good way" to code in kotlin is, especially when I'm converting from the good ol' java code.
    // autoconverted from java
        @Transactional
        fun leaveMembership(membershipNo: Long): Boolean {
            val membership = repository.selectOne(membershipNo) ?: return false
            membershipDeletedService.insertExpireHistory(membership)
            repository.delete(membershipNo)
            return true
        }
    // futile attempt to use as much kotlin stuff
        @Transactional
        fun leaveMembership(membershipNo: Long): Boolean = repository.selectOne(membershipNo)?.let {
            membershipDeletedService.insertExpireHistory(it)
            repository.delete(membershipNo)
            true
        } ?: false
    Which is more "kotlin-esque"? Or rather, which code do you think is better? If both are bad, how can it be refactored?
    d
    m
    • 3
    • 2
  • x

    Xabier Gorostidi

    11/26/2019, 10:06 AM
    Hello, does anybody know why I’d get
    NSInvalidArgumentException', reason: '*** -getValue: only defined for abstract class.  Define -[KotlinInt getValue:]!
    error when using a Kotlin/Nativei library from Swift?
    fun testMap(): Map<Int, Int> {
        return mutableMapOf(
            Pair(0, 1))
    }
    v
    • 2
    • 5
  • k

    kartikpatodi

    11/26/2019, 10:36 AM
    Is there a way in Kotlin to match a string but not within the quotes
    "
    or comments ? I need it as utility that searches for a text or pattern in kt files but not if it is inside string literal or comments.
    d
    m
    • 3
    • 4
Powered by Linen
Title
k

kartikpatodi

11/26/2019, 10:36 AM
Is there a way in Kotlin to match a string but not within the quotes
"
or comments ? I need it as utility that searches for a text or pattern in kt files but not if it is inside string literal or comments.
d

diesieben07

11/26/2019, 10:39 AM
You probably need a full-blown parser to do this properly. Check out https://github.com/kotlinx/ast
👍 1
k

kartikpatodi

11/26/2019, 11:07 AM
Is there a way with regex?
d

diesieben07

11/26/2019, 11:09 AM
Probably maybe? But its definitely the wrong tool for the job.
💯 1
m

Matteo Mirk

11/26/2019, 6:24 PM
always relevant: https://stackoverflow.com/a/1732454/255931
View count: 1