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

    harsh

    11/23/2020, 6:59 PM
    Now kotlin allow to add new file with these types too ☺️
    😎 2
    n
    a
    +2
    • 5
    • 4
  • k

    Kirill Grouchnikov

    11/23/2020, 10:35 PM
    Is there a Kotlin "idiomatic" one-liner counterpart of Java's
    Collections.unmodifiableList
    ?
    c
    • 2
    • 2
  • k

    Kirill Grouchnikov

    11/23/2020, 10:37 PM
    Right, but it can be cast to MutableList
    a
    • 2
    • 1
  • k

    Kirill Grouchnikov

    11/23/2020, 10:39 PM
    listOf
    creates a whole new list. Java's
    unmodifiableList
    is a very thin wrapper that throws exceptions on trying to modify the contents of the wrapped list
    e
    n
    +3
    • 6
    • 65
  • s

    Slackbot

    11/24/2020, 10:22 AM
    This message was deleted.
    b
    • 2
    • 1
  • m

    Mejiomah17

    11/24/2020, 11:32 AM
    Hello there! In my kotlin project IDEA extrimly slow. Syntax highlighting of 500 lines file takes up to minute. How can I help JB team improve performance of syntax highlighting?
    c
    b
    +2
    • 5
    • 19
  • b

    Bernhard

    11/24/2020, 2:32 PM
    is there a typesafe way to do partial application in kotlin? I’ve got a bunch of objects with a run method that receives a variable amount of different parameters and I need to make it fit an interface which takes only one common parameter. Not super keen on creating a factory class per object.
    n
    n
    k
    • 4
    • 19
  • b

    Bernhard

    11/24/2020, 2:57 PM
    interface Importer {
    fun run(value: String): String
    }
    val x = listOf(
    Importer { it.replace("h", "o")}
    )
    Gives me this on Kotlin 1.4.20: Interface Importer does not have constructors Unresolved reference: it
    k
    • 2
    • 2
  • t

    Tomas Kormanak

    11/24/2020, 3:03 PM
    Hi, I am updating a project to Kotlin 1.4 but I am getting this error when I try to build it
    Plugin org.jetbrains.kotlin:kotlin-maven-plugin:1.4 or one of its dependencies could not be resolved: Failure to find org.jetbrains.kotlin:kotlin-maven-plugin:jar:1.4
    Am I missing something?
    v
    • 2
    • 2
  • m

    manlan

    11/24/2020, 5:43 PM
    How to pass a value to an object class?
    r
    c
    n
    • 4
    • 6
  • n

    Ncrnomarkovic

    11/24/2020, 7:15 PM
    1st time using Fuel to make an http request and parse it into an object using the following tutorial: https://medium.com/@paul.allies/kotlin-http-get-with-deserialization-with-fuel-12691904e30b I don't understand the part about Gson. Looks like I don't have it defined in my gradle. Is this article's implementation the way to go? Is Fuel a good networking and parsing library? Advice appreciated - thank you
    Untitled
    d
    • 2
    • 2
  • c

    Chilli

    11/24/2020, 11:53 PM
    Why don't I have the
    AutoCloseable.use(...)
    function? It should be there, according to the stdlib documentation...
    Untitled
    e
    • 2
    • 20
  • u

    user

    11/25/2020, 6:13 PM
    Server-side with Kotlin Webinar Series Kotlin is becoming a language of choice for server-side application development. Null safety, 100% Java interoperability, coroutines, and many other features make Kotlin ideal for backend programming. We’re launching a series of webinars to help you to learn more about backend development with Kotlin or even try it for the first time. In the next […]
    h
    • 1
    • 1
  • a

    Akash Veerappan

    11/25/2020, 10:17 PM
    Hello everyone! I am new to opensource and kotlin. I have however been coding for the last five years though. I am keen on entering the opensource world and I would love to get some advice on where to get started with kotlin, as I hope to pick the language up as well. So, please let me know on where I could get started contributing. Thank you!
    👀 1
    a
    • 2
    • 1
  • i

    Ifvwm

    11/26/2020, 7:02 AM
    class OnlyAudioRecorder public constructor(val hadoopAddr: String, val kafkaAddr: String ){
     companion object{
      val instance:OnlyAudioRecorder by lazy (mode = LazyThreadSafetyMode.SYNCHRONIZED){
                OnlyAudioRecorder(hadoopAddr, kafkaAddr)
            }
        }
    // why this hadoopAddr and kafkaAddr are not referenced?
    a
    a
    a
    • 4
    • 10
  • c

    Cicero

    11/26/2020, 12:57 PM
    I had this
    abstract class AbstractResourceTopic(val state: ResourceState? = null, val isOn: Boolean? = null) {
        abstract val resourceType: ResourceType
    }
    and this
    fun AbstractResourceTopic.getIcon(): Int {
        this.state?.let {
            return when (it.state) {
                0 -> getStateZeroIcon()
                1 -> getStateOneIcon()
                2 -> getStateTwoIcon()
                else  -> getStateZeroIcon()
            }
        }
        this.isOn?.let {
            return if (isOn) getOnIcon() else getOffIcon()
        }
        return getStateZeroIcon()
    }
    I turned into this
    abstract class AbstractResourceTopic {
        constructor(state: ResourceState)
        constructor(isOn: Boolean)
        abstract val resourceType: ResourceType
    }
    and I don’t know how to create extension classes for this two different constructors
    fun AbstractResourceTopic.getStateIcon(): Int {
            return when (it.state) {
                0 -> getStateZeroIcon()
                1 -> getStateOneIcon()
                2 -> getStateTwoIcon()
                else  -> getStateZeroIcon()
            }
        }
    }
    fun AbstractResourceTopic.getIsOnIcon(): Int {
        return if (isOn) getOnIcon() else getO
    }
    This is not working and I couldn’t find the correct syntax or if I can even do this
    r
    n
    • 3
    • 5
  • r

    ribesg

    11/26/2020, 2:23 PM
    Why can’t you have a
    vararg
    of
    inline class
    type?
    m
    • 2
    • 1
  • j

    Jrichards1408

    11/26/2020, 2:49 PM
    is this creating two vals?
    :yes: 5
    t
    a
    • 3
    • 13
  • m

    Martin Barth

    11/26/2020, 3:19 PM
    is there a way of having a dispatch table like that without the
    !!
    all over the place?
    val extractor = when {
                config.contains(REGEX) && config.contains(FORMAT)  -> FormatAndRegexExtractor(config[REGEX]!!, config[FORMAT]!!)
                config.contains(REGEX) && !config.contains(FORMAT) -> NamedCaptureGroupExtractor(config[REGEX]!!)
                config.contains(DELIMS) && config.contains(FIELDS) -> DelimiterExtractor(config[DELIMS]!!, config[FIELDS]!!)
                else                                               -> throw IllegalArgumentException("can not process this configuration: $config")
            }
    d
    • 2
    • 2
  • a

    allan.conda

    11/26/2020, 5:07 PM
    Is it possible to differentiate between a parameter being passed to a function and
    null
    in Kotlin?
    fun <T> aFunctionWithOptionalParam(
        optionalParam: T? = null
    ) {
        if (/* optionalParam is set*/) {
            someCallbackIfSet()
        }
    }
    
    fun whatIWant() {
        aFunctionWithOptionalParam(1) // callback is invoked
        aFunctionWithOptionalParam(null) // callback is invoked
        aFunctionWithOptionalParam() // callback should not be invoked
    }
    w
    v
    +4
    • 7
    • 88
  • i

    Ifvwm

    11/27/2020, 3:21 AM
    val instance:OnlyAudioRecorder by lazy (mode = LazyThreadSafetyMode.SYNCHRONIZED){
             OnlyAudioRecorder(h,k)}
    // what does by lazy (mode = ...) { ... } mean?  should lazy take a lambda? but (...) {...} is not a lambda
    n
    e
    v
    • 4
    • 10
  • i

    Ifvwm

    11/27/2020, 5:11 AM
    what's different among "use" "by" "as"?
    n
    e
    • 3
    • 2
  • c

    Charlie Brown

    11/27/2020, 7:09 AM
    I face a confuse problem during learning Kotlin on hyperskill: https://hyperskill.org/learn/step/10784, here is there detail:
    //Consider the code snippet below. What will it print?
    
    var num = 0
    println(num++ + ++num)
    Here is my step
    num++ + ++num     (num = 0)
    num++ + 1         (num = 1)
    1 + 1             (num = 1)
    Am i correct?
    j
    t
    n
    • 4
    • 6
  • g

    German Politov

    11/27/2020, 10:08 AM
    Hi! Can I access
    <http://java.io|java.io>.InputStream
    in Kotlin? When I converted Java class(that had
    InputStream
    type field) to Kotlin that field was accessible in Kotlin, but when I created a new Kotlin class in Kotlin project InputStream was not accessible like it's presented on screenshot.
    m
    v
    t
    • 4
    • 15
  • t

    t0yger

    11/27/2020, 10:22 AM
    Hi! I want to define an extension variable. However, as you all know, I don’t have a field because I can’t initialize it. How do you implement it?
    interface Test {
        val a: String
    }
    
    var Test.b: String
        get() = field
        set(value) = field = value
    t
    • 2
    • 6
  • i

    Ivan Pavlov

    11/27/2020, 11:38 AM
    Hi. Does anyone know why delegation for
    fun
    interface with lambdas (
    class D
    ) doesn't work? I'd really want to use delegation that way, not like
    class C
    fun interface A {
        fun f()
    }
    
    fun interface B {
        fun f()
    }
    
    class C(b: B) : A by A(b::f) //works
    
    class D(b: B) : A by { b.f() } //doesn't work
    v
    e
    • 3
    • 5
  • u

    user

    11/27/2020, 2:23 PM
    GitLive Case Study: Kotlin Multiplatform Across Desktop and Mobile GitLive uses Kotlin Multiplatform to share code between IDE plugins (for all JetBrains IDEs and VSCode), as well as soon-to-be-released mobile applications for iOS and Android. A team of 5 working on the project have written over 12k lines of Kotlin code as a shared library used by 4 different platforms: Android, iOS, JVM and […]
    :kotlin-intensifies: 7
    d
    m
    • 2
    • 2
  • n

    Nikky

    11/27/2020, 8:09 PM
    i have something REALLY weird happening in my project right now.. one would expect a main function to implicitely do
    exitProcess(0)
    but it does not.. when i run this from within idea it just hangs at the end
    b
    n
    g
    • 4
    • 16
  • c

    Chilli

    11/27/2020, 8:52 PM
    Hey, I can't really understand the difference between Iterator and Iterable. They both seem to perform the same function, so I want to ask: what's the difference between them and when to use which one?
    e
    b
    +2
    • 5
    • 15
  • c

    Chilli

    11/27/2020, 9:42 PM
    Is there any stdlib kind of Iterator that allows to “go back” (like .previous()) or at least “see” the next element without actually calling .next() and therefore making it advance?
    d
    t
    +2
    • 5
    • 39
Powered by Linen
Title
c

Chilli

11/27/2020, 9:42 PM
Is there any stdlib kind of Iterator that allows to “go back” (like .previous()) or at least “see” the next element without actually calling .next() and therefore making it advance?
d

Dominaezzz

11/27/2020, 9:43 PM
List iterators allow that iirc.
The going back I mean.
Peeking is not part of the Java iterator API sadly.
c

Chilli

11/27/2020, 9:49 PM
That's a shame—I kinda need to do that with a sequence and I don't want it to calculate all the elements (cause I presume to make a list iterator I'd need a list)
d

Dominaezzz

11/27/2020, 9:50 PM
Yeah you'd need a a list.
You could keep track of the previous element or maybe
zip
might help?
t

Tobias Berger

11/27/2020, 9:51 PM
That's right. ListIterator defined a
previous()
function. Peeking (looking at the next element without progressing) is not included, which might be a good thing because in some cases it could lead to unexpected behaviour. However, you could implement your own "PeakingIterator" (or use the one from apache commons if you're on JVM)
n

Nir

11/27/2020, 9:55 PM
@Chilli if you need to provide a peek function that's relatively straightforward, I think, or at least more straighforward than anything else discussed
basically all you need is an iterator that buffers one element
c

Chilli

11/27/2020, 9:56 PM
True, I think I'll try making one myself so I don't need a list nor any extra library
t

Tobias Berger

11/27/2020, 10:05 PM
Of course there are multiple ways to implement that. This is a kotlinized version of the Google/Guava implementation (com.google.common.collect.Iterators.PeekingImpl)
PeekingIterator_kt.kt
n

Nir

11/27/2020, 10:09 PM
Did you have it written with "Peak" everywhere a second ago? lol otherwise i may be having a stroke
o

okarm

11/27/2020, 10:10 PM
He will never tell :)))
t

Tobias Berger

11/27/2020, 10:10 PM
note that this implementation will fail if you call
peek()
and there are no more elements. A check for that could be added easily if you want that behaviour @Nir you're not having a stroke (I hope), I just had a brain fart when writing the class
n

Nir

11/27/2020, 10:10 PM
Okay, I started a comment pointing that out and then it changed with no "modified" thing in slack, phew
I agree with the basic idea of the implementation but I'm not sure I agree with the boolean and branching
I'd probably just implement it by always being one step ahead, seems simpler
t

Tobias Berger

11/27/2020, 10:14 PM
Yeah, I'm not so shure about that either. My first thought was basically copying Kotlin's own
AbstractIterator
implementation and exposing
nextValue
(or something that would look very similar). I wouldn't have written it like above myself, but it is shorter and part of a widely used Google lib, it should be ok.
Somehow Slack doesn't seem to mark edited text snippets as modified. Now I'm wondering, what would a "PeakingIterator" look like 🤔
n

Nir

11/27/2020, 10:17 PM
class PeekingIterator<T>(private val iterator: Iterator<T>) : Iterator<T> {
    
    fun Iterator<T>.nextOrNull() = if (iterator.hasNext()) iterator.next() else null
    
    var nextElement = iterator.nextOrNull()

    override fun hasNext() = (nextElement != null)

    override fun next(): T {
        val next = nextElement!!
        nextElement = iterator.nextOrNull()
        return next
    }

    fun peek() = nextElement
}
t

Tobias Berger

11/27/2020, 10:19 PM
should work for most cases, but you should limit the generic Parameter to
PeakingIterator<T: Any>
(not allowing nullable types). Having null values would break this implementation
n

Nir

11/27/2020, 10:20 PM
that's a great point
t

Tobias Berger

11/27/2020, 10:20 PM
and if you want to be pedantic, do
override fun next(): T {
        val next = nextElement ?: throw NoSuchElementException()
...
➕ 1
n

Nir

11/27/2020, 10:20 PM
hmm this is the second time recently in Kotlin that I've wanted a "private" nullable, if that makes sense
a nullable type where I'm the only one that can null it, and the "non-null state" can hold a null itself. If that makes sense.
I guess some sort of Optional<T> like thing, which would allow you to have Optional<Int?> if you so wanted for instance
t

Tobias Berger

11/27/2020, 10:22 PM
I know what you mean, had the same thought in my work project this week. Basically i want what JS has - a distinction between
null
and
undefined
n

Nir

11/27/2020, 10:25 PM
the thing about Kotlin which is a bit weird now that I think of it is that Kotlin effectively collapses nulls
t

Tobias Berger

11/27/2020, 10:25 PM
There was a question here yesterday about passing
null
for an optional parameter that also has
null
as its default value. Same issue.
n

Nir

11/27/2020, 10:25 PM
typically in languages with generics, and something like optional, it doesn't work that way
e.g. in C++, you have optional<T>, T itself can be say optional<int>, and then the outer type is optional<optional<int>>
not very useful in non-generic code, ok, but it is quite useful in generic code like this
t

Tobias Berger

11/27/2020, 10:27 PM
I mean you could do the same in Kotlin, you just usually wouldn't. I think we just got so used to Kotlin's null-handling (and we love it) that we forget that - sometimes -
null
can actually be an expected value.
And if that's the case, you can't use null-handling anymore to controll your flow, which you got used to by using
?.let
,
?:
, etc.
Sorry btw to anyone else who still get's notified for messages in this thread
➕ 1
n

Nir

11/27/2020, 10:34 PM
yeah the thing is that in generic code it can quite happen. Which IMHO really actually limits Kotlin's null usefullness in generic code
*quite easily happen
t

Tobias Berger

11/27/2020, 10:38 PM
I think I know what you mean. But I think in Kotlin you are actually able to handle that combination quite well. You can limit generic types to lock out nullable types and it you don't want that, you might be more aware of it and just implement it in a way where you don't use null for flow control (e.g. by using Optional-like wrappers). Something like Java is much worse, because you basically have no idea if something might be null.
n

Nir

11/27/2020, 10:39 PM
yeah the Java situation is definitely crazy, don't get me wrong.
View count: 2