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

    dhananjaykulkarni19

    06/19/2019, 5:49 AM
    Dear All, I want to build an instagram like stories feature. Any help / resources will be helpful. 🙏 TIA
    g
    • 2
    • 1
  • b

    bohsen

    06/19/2019, 8:58 AM
    I'm playing around with kotlin
    contracts
    and have run into a problem I need some expert help with. I'm trying to validate user input from a method that takes a couple of nullable parameters and would like to use
    contracts
    and the below
    checkParamIsNotNullOrBlank
    -function to avoid null checks at the end of my expression. Here's a simplified example of what I'm trying to achieve:
    @ExperimentalContracts
        override fun validateInput(
            firstParam: String?,
            secondParam: String?,
            thirdParam: String?,
            listener: ValidationListener?) {
            var error: Boolean
            error = isParamNullOrBlank(firstParam) { view?.firstParamEmptyError() }
            if (secondParam.isNullOrBlank()) {
                view?.secondParamEmptyError()
                error = true
            }
            if (thirdParam.isNullOrBlank()) {
                view?.thirdParamEmptyError()
                error = true
            }
            if (error == false) {
                val validObject = Object.Builder()
                    .withFirstParam(firstParam)
                    .withSecondAndThirdParam("$secondParam^$thirdParam")
                    .create
    
                listener?.onValidated(validObject)
            }
        }
    Here's my "contracts"-method:
    @ExperimentalContracts
    fun isParamNullOrBlank(param: String?, onInvalid: (() -> Unit)? = null) : Boolean {
        contract {
            returns(false) implies (param != null)
        }
        val result = param.isNullOrBlank()
        onError?.invoke()
        return result
    }
    This doesn't compile because the compiler can't infer that
    firstParam
    is not null. Also every
    if
    expression should be evaluated as the view can display multiple errors.
    k
    • 2
    • 2
  • i

    Ifvwm

    06/19/2019, 10:26 AM
    I don't understand why kotlin is so different to others
    g
    m
    +2
    • 5
    • 43
  • m

    mbonnin

    06/19/2019, 12:25 PM
    Is 1.3.40 released ? Looking at https://github.com/JetBrains/kotlin it seems to be the case but I can't find any announcement ?
    k
    • 2
    • 2
  • s

    spand

    06/19/2019, 1:53 PM
    Using jdk proxies and Kotlin kinda sucks since all checked exceptions are wrapped in
    UndeclaredThrowableException
    . What are people doing instead ?
    e
    • 2
    • 2
  • c

    cbruegg

    06/19/2019, 4:34 PM
    Is the new NPM integration also integrated with
    ts2kt
    ?
    l
    • 2
    • 1
  • h

    Hullaballoonatic

    06/19/2019, 5:53 PM
    I mean, I understand why this interaction works this way, but it still makes me sad ☹️ https://pl.kotl.in/_g7Nag0rP in my particular use case, it'd be nice if the
    Bar1
    was also added to
    foos
    , but I imagine in other cases, that would be horrendous
    r
    s
    l
    • 4
    • 18
  • j

    Joan Colmenero

    06/19/2019, 6:18 PM
    Using MVP - I have a call that returns for instance a number between 1-43, then I need to do something like if it's between 1 and 5 show this image, if it's between 6 and 29 another one, so since in Presenter I can't put anything about R and Android context, how do I let the view know which icon has to show? Because as far as I understand view doesn't have to do any logic. Or for instance, I get a Boolean from API and then from VIEW I want to show an image or another one, I thought about create showWhiteBackground() and showBlackBackground() and then call the correct one, this is ok if the value is between 2, but when it's between 1-43 I can not do something like this 😕
    s
    l
    • 3
    • 37
  • m

    mathew murphy

    06/19/2019, 6:36 PM
    So am I right in thinking that sequences built via yielding are necessarily unbuffered, and that if I want some buffering I'll need to use channels?
    g
    • 2
    • 2
  • h

    Hullaballoonatic

    06/19/2019, 6:44 PM
    is there a more clever way to accomplish this? maybe a way to generalize the behavior (delegation or annotation?), or does such a generalization already exist? https://pl.kotl.in/Z2joV2hL3
    class MyClass(foo: Int, bar: Int) {
        private var fooLock = false
        var foo = foo
        	set(v) {
                fooLock = true
                
                if (!barLock) bar += (v - field)
                field = v
                
                fooLock = false
            }
        
        private var barLock = false
        var bar = bar
        	set(v) {
                barLock = true
                
                if (!fooLock) foo += (v - field)
                field = v
                
                barLock = false
            }
    }
    s
    m
    k
    • 4
    • 17
  • m

    Matej Drobnič

    06/19/2019, 7:14 PM
    I'm a bit confused by "new inference is only enabled in IDE" statement. Doesn't new inference produce less compile errors? That would mean that IDE now warns about LESS errors before running compilation which could now still fail since compiler uses old inference. Or am I interpreting this statement wrongly?
    🤔 2
    n
    t
    k
    • 4
    • 4
  • p

    pavi2410

    06/19/2019, 8:00 PM
    In the latest 1.3.40 change log, I saw
    String.encodeToByteArray
    experimental API introduced there. And I have been using
    String.toByteArray
    since always. I want to know why there is such redundancy? What's the difference between them? (I don't think there is much or any difference at all)
    m
    g
    • 3
    • 5
  • m

    mathew murphy

    06/19/2019, 9:49 PM
    "Starting from Kotlin 1.3-RC2, serialization plugin is shipped with the rest of Kotlin compiler distribution, and the IDEA plugin is bundled into the Kotlin plugin." — https://github.com/Kotlin/kotlinx.serialization
    m
    • 2
    • 1
  • m

    mathew murphy

    06/19/2019, 9:53 PM
    So if I'm not using Gradle I need to add the library explicitly?
    l
    s
    • 3
    • 11
  • m

    Matt

    06/20/2019, 2:04 AM
    hey anyone know how to specify the json key for a field on an object in serialization? i.e. seriesUUID in the app but the api sends as series_uuid? am i stuck with the object having series_uuid?
    m
    • 2
    • 3
  • c

    camdenorrb

    06/20/2019, 2:56 AM
    I had to change like half my code base for using typeOf
    i
    i
    • 3
    • 12
  • i

    Ifvwm

    06/20/2019, 5:12 AM
    how I can create a type, that tpe contain String and Int?
    k
    k
    g
    • 4
    • 14
  • a

    Albert

    06/20/2019, 6:31 AM
    Why isn't it possible to pass a charset to
    ByteArray.decodeToString
    with kotlin 1.3.40?
    s
    g
    i
    • 4
    • 7
  • r

    Ruckus

    06/20/2019, 2:23 PM
    I'm seeing a weird new intention in 1.3.40, that I think has something to do with the new type inference. Is this a known bug?
    Weird_Intentions.kt
    g
    • 2
    • 4
  • i

    Ifvwm

    06/20/2019, 2:33 PM
    what’s the preferred library to do POST GET stuff? RESTFul API
    d
    g
    • 3
    • 9
  • r

    robstoll

    06/20/2019, 3:21 PM
    I updated to 1.3.40 and now intellij stopped to work (tons of
    KotlinIdeaResolutionException: Kotlin resolution encountered a problem while analyzing KtNameReferenceExpression
    ) how can I downgrade the kotlin plugin?
    ✔️ 1
    a
    • 2
    • 3
  • d

    dMusicb

    06/20/2019, 5:16 PM
    Is it bad to put helper functions on a data class? For example say I have data classes that hold configuration/setting data for different kinds of actions. There can be lots of different types so it has a type field. Eventually I need to map it to the actual action class with business logic that uses the configuration/setting data. I could do a when(type) and instantiate respective action class and pass in the config data class. Or could I add something like: fun toActionClass(): SpecificActionClass = SpecificActionClass(this)
    d
    e
    • 3
    • 8
  • a

    Allan Wang

    06/20/2019, 6:24 PM
    Is there a good way to declare that a function returns a nonnull type, where the generic used is nullable? For instance:
    interface Call<T> {
        suspend fun call(): T
    }
    
    suspend fun <T> Call<T>.callNotNull(): T = call() ?: throw RuntimeException("Example")
    
    val nonnullCall = object : Call<String> {
        override suspend fun call(): String = "notnull"
    }
    
    val nullCall = object : Call<String?> {
        override suspend fun call(): String? = null
    }
    
    suspend fun t() {
        val r: String = nonnullCall.callNotNull()
        val s: String = nullCall.callNotNull()
    }
    At its current state, I will get an error for
    nullCall
    since
    s
    is
    String?
    Type
    T
    may or may not be nullable, but the returning type is definitely not null. I can’t use contracts because this is a suspended function I can’t make the extension to
    Call<T?>
    or it won’t work for
    nonnullCall
    Do I have to make two extension functions for this to work? Is there something like
    T!
    that would indicate a type with nullability removed?
    r
    • 2
    • 3
  • r

    Ruckus

    06/20/2019, 9:57 PM
    I think I found another issue with the new type inference:
    fun fred(map: Map<String, Any?>) {
        ...
    }
    
    fun test() {
        fred(mapOf("a" to { x: Color -> x.grayValue() }, "b" to Color.BLUE))
    }
    The
    { x: Color -> x.grayValue()}
    is marked as an error due to
    Type mismatch
    Required: Color
    Found: (Color) -> UByte
    But it compiles and runs fine
    • 1
    • 1
  • r

    Ruckus

    06/20/2019, 10:02 PM
    And another:
    fun getResult(value: Any?) {
        val result = (value as? Map<*, *>)?.get("result")
        ....
    }
    The
    get
    call is marked as an error due to
    Type inference failed. The value of the type parameter K should be mentioned in input types (argument types, receiver type or expected type). Try to specify it
    But again it compiles and runs fine
    g
    a
    • 3
    • 5
  • v

    ValV

    06/21/2019, 1:26 AM
    I'm writing a simple app in vim + gradle:
    class App {
      val listA = listOf(1, 8, 12, 17, 26, 31)
    }
    
    fun main(args: Array<String>) {
      val app = App()
      while (app.listA.hasNext()) {
        println(app.listA.next())
      }
    }
    But get this on
    gradle run
    Unresolved reference: hasNext
    Unresolved reference: next
    Have I forgot something? Something in Gradle?
    n
    g
    • 3
    • 12
  • v

    ValV

    06/21/2019, 5:22 AM
    Another obscure thing for me, why is this kind of mapping not possible?
    fun main() {
        val a = listOf(listOf(32,53,23), listOf(13), listOf(34))
        val its = a.map(it.iterator())
        println(its)
    }
    map(it.iterator())
    l
    g
    • 3
    • 7
  • a

    Alexjok

    06/21/2019, 7:57 AM
    I have case where i need to find all duplicates in list by code and finally get values from duplicateList with lower dateTime. Any ideas?
    fun main() {
          val fileList = listOf<FileName>()
    }
    
    data class FileName(val code: String, val uid: String, val dateTime: LocalDateTime)
    d
    • 2
    • 5
  • a

    Antanas A.

    06/21/2019, 8:18 AM
    Hi, is there a way to write anonymous suspend function? ``` val func = { // <- here I cannot call suspend functions } ``
    t
    s
    d
    • 4
    • 14
  • i

    Ifvwm

    06/21/2019, 10:31 AM
    about type inheritance, Can I make a type which inherite Int and String? and how?
    d
    g
    s
    • 4
    • 4
Powered by Linen
Title
i

Ifvwm

06/21/2019, 10:31 AM
about type inheritance, Can I make a type which inherite Int and String? and how?
d

diesieben07

06/21/2019, 10:32 AM
Both
Int
and
String
are final, so no, you cannot inherit from them.
g

gildor

06/21/2019, 10:33 AM
even if you could, I would still use Either
👍 1
s

Stephan Schroeder

06/21/2019, 3:02 PM
in case you’re looking for Either now. You’ll find it in the arrow lib: https://arrow-kt.io/docs/arrow/core/either/
Either<Int, String?>
is probably what you’re looking for assuming your variable is fine with being either an
Int
or a
String?
, but not both at the same time.
View count: 1