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

    RafaelLange

    11/10/2020, 2:55 AM
    I've been facing this problem for a while. Each time I press ctrl + space to open a suggestion, Intellij tries to index something and close a suggestion window. Has anyone had a problem like this?
    d
    m
    +3
    • 6
    • 9
  • x

    xiaobailong24

    11/10/2020, 4:57 AM
    https://kotlinlang.org/docs/reference/ Kotlin lastest version is 1.4.10. But I want refer to v1.3.72 docs, how do that? Help me. What link is kotlin old version docs?
    g
    v
    • 3
    • 6
  • a

    Ananiya

    11/10/2020, 8:57 AM
    hello there, i may have this kind of code
    fun main(){
      val list =  listOf(1, 10,-1, -2, 3,12)
      val joined = list.joinToString(" + ")
      println("${joined} = 10")
    }
    which prints the list as string with + sine added(
    "1 + 10 + -1 + -2 + 3 + 12 = 10"
    ). but i wan't it to really add and return either true or false. how can i do that
    m
    v
    • 3
    • 3
  • a

    Astronaut4449

    11/10/2020, 10:40 AM
    fun foo() = println("No receiver")
    fun Int.foo() = println("My receiver is $this")
    with(42) { foo() } // will print 'My receiver is 42' but I want 'No receiver'
    Is it somehow possible to call the function without receiver, although one is given by the current scope?
    b
    v
    • 3
    • 5
  • t

    thana

    11/10/2020, 12:37 PM
    hi, is there a compiler setting to mark all objects returned by java methods nullable? e.g. we are using jooq, a library to write type safe sql queries. it has several
    fetch
    methods, all of which might or might not return a value, depending on what the sql returns. The compiler doesn;t recognize it's nullable and so we are always in danger to produce NPEs...
    n
    g
    j
    • 4
    • 8
  • n

    Nick

    11/10/2020, 2:39 PM
    view.findViewById<AppCompatTextView>(
        R.id.strike_price
    )?.let {
        it.text = price.toString()
    }
    Would you
    nit
    this, or request changes? 1️⃣ nit 2️⃣ request changes, unnecessary use of
    let
    3️⃣ 1
    2️⃣ 12
    s
    n
    +2
    • 5
    • 6
  • u

    ursus

    11/11/2020, 1:06 AM
    What's your opinion on using top level functions with capital letter as factory functions? I notice people doing this more and more
    fun User(...) : User? {
       // if invalid input return null
       return User(..)
    }
    
    data class User(...)
    a
    a
    +2
    • 5
    • 8
  • n

    Nuru

    11/11/2020, 7:55 AM
    According to the official documentation, "SAM conversions only work for interfaces, not for abstract classes, even if those also have just a single abstract method." But I just tried it with an Abstract Class and it seems to work. Did I not understand the documentation properly or this is now possible in New Kotlin version? 🤔 https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions
    n
    • 2
    • 4
  • j

    jro

    11/11/2020, 9:03 AM
    Is
    foo
    being
    null
    inside the init block expected behavior? Doesn't seem right for a property that's declared not null. Printing
    foo
    directly results in an error. Run code in kotlin playground
    e
    a
    +2
    • 5
    • 17
  • e

    elect

    11/11/2020, 11:18 AM
    sometimes I find my self misusing the
    @Deprecated
    annotation just to remind me some critical logic when using a specific variable (in the context of some native code port).. has anyone a better idea?
    c
    h
    n
    • 4
    • 6
  • s

    spand

    11/11/2020, 12:19 PM
    Any better workaround for nullable destructuring?
    val (p1,p2) = pair ?: null to null
    a
    i
    n
    • 4
    • 12
  • e

    elect

    11/11/2020, 3:28 PM
    is there a way to sort only a ArrayList subrange?
    v
    c
    s
    • 4
    • 12
  • d

    df

    11/11/2020, 11:28 PM
    while (value.links.next != null) {
    any chance to smartcast value.links.next to non-null inside the loop? Basically looking for a counterpart to
    nullable?.let { it is not null }
    r
    v
    +3
    • 6
    • 16
  • r

    ron

    11/12/2020, 11:53 AM
    Any jetbrains people around that can answer some questions about
    code with me
    ?
    g
    • 2
    • 1
  • g

    Geert

    11/12/2020, 1:35 PM
    I’m trying to add a property to an interface with a default value, that is no problem. But thats a function,  and I need a property that can change Why isn’t contracts supported for properties? This is my code:
    interface PrimitiveType<T> {
        var value: T?
    }
    
    interface Defaultable<T> {
        var defaultValue: T
    }
    
    @ExperimentalContracts
    fun <T> PrimitiveType<T>.defaultValue() : T {
        contract {
            returns() implies ( this@defaultValue is Defaultable<*>)
        }
    
        return this.value!!
    }
    
    
    @ExperimentalContracts
    fun <T> PrimitiveType<T>.editValue() : T {
        contract {
            returns() implies ( this@editValue is Defaultable<*>)
        }
    
        return this.value!!
    }
    
    @ExperimentalContracts
    fun <T> PrimitiveType<T>.setEditValue(value: T) {
        contract {
            returns() implies ( this@setEditValue is Defaultable<*>)
        }
    
        this.value = value
    }
    d
    • 2
    • 1
  • r

    ribesg

    11/12/2020, 2:23 PM
    Does this create one million lists of the 2 same strings or is this optimized somehow? I’m used to declaring such list of accepted values as a
    val
    before but I’m not sure if it’s needed
    myListWithOneMillionElements.filter { it.a in listOf("a", "b") }
    k
    • 2
    • 1
  • a

    Alexander Black

    11/12/2020, 2:52 PM
    This is a bit of a n00bish question… but if I’m trying to match an email pattern with a regex… and I have some pattern “patern”.toRegex()… what is the proper way to find out if a string matches that regex? in my case I’m using the RFC email address regex to validate, but I’m getting false results when I do. Here’s the link to the regex
    val regex = "Regex here".toRegex()
    regex.matches("<mailto:first.last@test.com|first.last@test.com>")
    what am I missing?
    r
    s
    t
    • 4
    • 53
  • e

    Ewan

    11/12/2020, 3:40 PM
    I have an Android project in AndroidStudio 4.2 Canary 16 which has a dependency on an external Kotlin library locally published to maven (written in Idea 2020.2). Both project and library use Kotlin 1.4.10 and the new backend compiler. The problem I have is that I'm able to execute Android code which refers to objects from the Kotlin library but cannot access the objects directly during debugging via breakpoints or using Evaluate Expression. For example given library class
    class Person(val name: String) {
    fun greeting() = "Hello, I'm $name"
    }
    I can run this test in Android Studio:
    class ExampleUnitTest {
    @Test
    fun name() {
    val person = Person("Jane")
    assert(person.name == "Jane")
    }
    }
    but... If I set a non-suspending breakpoint to print out the value of person.name or a set a suspending breakpoint and use Evaluate Expression to evaluate person.name I get the error: Class 'uk.co.telesense.controller.Person' is compiled by a new Kotlin compiler backend and cannot be loaded by the old compiler If I debug the test with no breakpoints it runs green. Any idea what's going on here? In the kotlin library I have:
    compileKotlin {
    kotlinOptions.useIR = true
    }
    compileTestKotlin {
    kotlinOptions.useIR = true
    }
    in the Android Studio project I have
    buildscript {
    ext.kotlin_version = '1.4.10'
    ...
    dependencies {
    classpath 'com.android.tools.build:gradle:4.2.0-alpha15'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
    ...
    }
    I hope that makes sense! Any ideas?
    z
    • 2
    • 2
  • m

    Martin Barth

    11/12/2020, 4:03 PM
    I've got a class that has a constructor with a single parameter and I want to add a couple of different "public" read only members to the class as well. there is a expensive algorithm to calculate the values of each of the members based on the constuctur parameters. How can I run the algorithm only once and populate vals?
    d
    c
    n
    • 4
    • 14
  • n

    Nish Patel

    11/12/2020, 5:13 PM
    Hi everyone, i'm new to kotlin and i need help in regarding parsing json to sealed class using kotlin.serialization library, whats the difference between serializer and serialName
    m
    • 2
    • 2
  • a

    Ananiya

    11/12/2020, 6:32 PM
    Is there any HTTP request kotlin standard library which is wrapped with kotlin.jvm why I am asking this is most of online compilers like repl, sololearn, play kotlin have no gradle support which wont let me use libs like okhtpp..
    z
    p
    • 3
    • 4
  • a

    akuleshov7

    11/12/2020, 8:16 PM
    https://akuleshov7.com/2020-11-10-kotlin-static-analyzers.html
    n
    j
    n
    • 4
    • 6
  • p

    Patrick Ramsey

    11/12/2020, 11:33 PM
    In kotlin-multiplatform targeting js, Long values are represented as an object containing the top and bottom 32 bits of the value as separate fields ({low: lowbits, high: highbits, value: zzzzzzzzzz}) . Is there any way to hint to the compiler that the values are less than Number.MAX_SAFE_INTEGER, and that they should be represented in javascript as a bare Number, or to otherwise pass a number greater than 1<<31 back into native javascript code?
    c
    • 2
    • 4
  • f

    FareesHussain

    11/13/2020, 1:26 AM
    https://codingcompetitions.withgoogle.com/kickstart/round/000000000019ffc7/00000000001d3f56 i was trying to solve this using kotlin my code passes the test cases but after submission it doesn't get accepted (same algo is accepted for c++ code ) please help
    a
    • 2
    • 11
  • e

    Exerosis

    11/13/2020, 11:48 AM
    What would the best place be to post suggestions for the Kotlin language on the whole? I'm digging into Jetpack Compose and it seems like they ran into the same issue I keep struggling with. The simple lack of "multi extension" functions. IDK if there is a good reason they don't already exist, or if someone has already proposed they just be added to the language, but I think they would be hugely useful. eg.
    data class First(
        val partOfFirst: String
    )
    data class Second(
        val partOfSecond: String
    )
    fun First.Second.multiExtension() {
        println(partOfFirst + partOfSecond)
    }
    fun main() {
        First("hello ").apply {
            Second("world").apply {
                //possible because First and Second are both in this scope.
                multiExtension()
            }
        }
    }
    e
    k
    • 3
    • 2
  • a

    andreasmattsson

    11/13/2020, 12:46 PM
    class C
    object O {
        operator fun C.plus(other: C): C = this
        operator fun C.inc(): C = this
    }
    Could anyone please explain to me why the second function (inc) is illegal/doesn't compile, but the first is okay (plus)? Fails with
    'operator' modifier is inapplicable on this function: receiver must be a supertype of the return type.
    Isn't the receiver (
    C.
    ) a supertype of the return type (
    : C
    ) in both cases? This compiles and runs if I move the fun declaration of inc outside the object to root level BTW.
    🤔 1
    t
    v
    • 3
    • 8
  • t

    TwoClocks

    11/13/2020, 9:00 PM
    Is there a generally accepted pattern to deal with variables that never change after being set, but they arn't known at object construction time? lateinit helps w/ the late-part, but not the val part. It'd be nice if the compiler could help if anyone is trying to change it.
    c
    n
    +3
    • 6
    • 16
  • f

    Florian

    11/13/2020, 9:22 PM
    is there any benefit in declaring the types of the lambda parameters?
    a
    i
    e
    • 4
    • 20
  • a

    andreasmattsson

    11/13/2020, 10:17 PM
    Ran into another issue in my codebase. It took me a little while to track it down, but I suspect it might be a compiler error? Seems data classes don't play well with overriding interface properties with
    @JvmField
    annotations:
    interface Interface {
        val value: Int
    }
    
    data class Implementation(@JvmField override val value: Int) : Interface
    
    class Test {
        @Test
        fun test() {
            assertEquals(Implementation(123), Implementation(123))
        }
    }
    It works if I do one of three things: • don't override the interface variable • remove the
    @JvmField
    annotation • make it a normal (non-data class) Dunno if this is intended to not be permitted, or a bug in the generated
    equals
    code. Either way if I leave it as is it compiles, but then throws an exception at runtime:
    e
    • 2
    • 6
  • w

    Wilhelm Fitzpatrick

    11/14/2020, 1:37 AM
    Inspired by IntStream.iterate in modern versions of Java, I was interested in having function that would create a sequence of values that could be specified and would behave much like a classic indexed for loop. I cobbled something up using generateSequence, but I'm wondering if there is something in the actual standard library that does something close to this already...
    fun <T> iterate(seed: T, predicate: (T) -> Boolean, transform: (T) -> T): Sequence<T> {
        var current = seed
        return generateSequence() {
            if (!predicate(current)) null
            else {
                val was = current
            	current = transform(was)
                was
            }
        }
    }
    
    val seq: Sequence<Int> = iterate(0, { it < 1000 }, { it * 2 + 1 })
    
    fun main() { println(seq.toList()) }
    
    [0, 1, 3, 7, 15, 31, 63, 127, 255, 511]
    n
    e
    • 3
    • 9
Powered by Linen
Title
w

Wilhelm Fitzpatrick

11/14/2020, 1:37 AM
Inspired by IntStream.iterate in modern versions of Java, I was interested in having function that would create a sequence of values that could be specified and would behave much like a classic indexed for loop. I cobbled something up using generateSequence, but I'm wondering if there is something in the actual standard library that does something close to this already...
fun <T> iterate(seed: T, predicate: (T) -> Boolean, transform: (T) -> T): Sequence<T> {
    var current = seed
    return generateSequence() {
        if (!predicate(current)) null
        else {
            val was = current
        	current = transform(was)
            was
        }
    }
}

val seq: Sequence<Int> = iterate(0, { it < 1000 }, { it * 2 + 1 })

fun main() { println(seq.toList()) }

[0, 1, 3, 7, 15, 31, 63, 127, 255, 511]
n

Nir

11/14/2020, 1:45 AM
I'm confused how generate sequence doesn't already do what you want?
It seems like the only difference is taking two separate lambdas as predicate + transform vs just nullable transform
e

ephemient

11/14/2020, 1:46 AM
val seq = generateSequence(0) { it * 2 + 1 }.takeWhile { it < 1000 }
☝️ 2
w

Wilhelm Fitzpatrick

11/14/2020, 3:24 AM
@Nir I like the idea of being able to specify the predicate and transform separately, that's all. It makes adapting imperative code more straightforward by directly mirroring the for loop syntax.
🤔 1
@ephemient yeah, my version started out closer to yours, generateSequence with a seed always returns the seed, which a for loop won't do if the predicate fails on the initial version. I'm sure there is a better way to rephrase it, Just wanted to make sure I wasn't overlooking something in the standard lib.
e

ephemient

11/14/2020, 3:34 AM
if you don't want the seed to appear in the sequence, you could
.drop(1).takeWhile { ... }
I don't imagine it's common to want a value in the sequence which break the predicate (first value or not)
.withIndex().filter { (index, value) -> index == 0 || ... }.map { it.value }
would let the first item pass regardless
but for the generate scenario,
sequenceOf(seed) + generateSequence(transform(seed), transform).takeWhile(predicate)
would be clearer most of the time, IMO
View count: 2