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

    louiscad

    08/29/2019, 1:21 PM
    Hi, I want to use the new J2K (Java to Kotlin converter) that should have been made available by Kotlin 1.3.50 IDE plugin, but I'm not finding the
    Use New J2K (experimental)
    settings flag in the IDE after using the search feature with the "J2K" words. Has the actual setting been forgotten to be added/enabled for use?
    w
    • 2
    • 2
  • m

    Marcin Wiśniewski

    08/29/2019, 6:45 PM
    Ok, I found solution by myself 🙂
    👍 2
    a
    • 2
    • 2
  • g

    Greg Stepniewski

    08/30/2019, 7:57 AM
    Going through the Coroutines documentation (https://kotlinlang.org/docs/reference/coroutines/exception-handling.html) and I found this:
    If a coroutine encounters exception other than CancellationException, it cancels its parent with that exception. This behaviour cannot be overridden and is used to provide stable coroutines hierarchies for structured concurrency.
    However, you have SupervisorJob which says
    A failure or cancellation of a child does not cause the supervisor job to fail and does not affect its other children.
    These two seem to contradict, since SupervisorJob clearly overrides the behaviour of children cancelling their parent on failure - or am I missing something?
    c
    m
    s
    • 4
    • 6
  • s

    svenjacobs

    08/30/2019, 8:26 AM
    Let's assume I have a public extension function in a class or interface
    class A {
        fun String.hello() = "hello $this"
    }
    Is there any simpler solution of calling this function instead of having to use
    with()
    ?
    val a = A()
    "Some string".run {
        with(a) { hello() }
    }
    s
    m
    • 3
    • 12
  • c

    Czar

    08/30/2019, 11:34 AM
    Hi. I'm trying to design a nice API around entities in a kotlin project with JPA. In a legacy project we have been plagued with
    val entity =  repository.getOne(entityId)
    val entityId = checkNotNull(entity.id) { "Entity id cannot be null if it is retrieved from the database" }
    all over the place. In the new project first we thought of using contracts, but their restrictions make them useless for this case, so this more crude idea was born:
    abstract class BaseEntity<T : Serializable> {
    	/**
    	 * Direct use of `_dbId` is strongly discouraged in business level code, this should only be used on the persistence
    	 * level by the framework and related infrastructure code.
    	 */
    	@Suppress("PropertyName")
    	protected abstract val _dbId: T?
    	/**
    	 * Accessing `id` implies that entity has been retrieved from a repository or crafted with a pre-set identifier.
    	 * If this condition is not met, accessing it will generate an `IllegalStateException`.
    	 */
    	@get:Transient
    	val id: T
    		get() = checkNotNull(_dbId) { "Entity has not been saved" }
    }
    Any thoughts? Improvements? Maybe better alternatives? In this here case, implementation would look like:
    @Entity(name = "clients")
    class InfoEntity(
    	@Id
    	@GeneratedValue(strategy = GenerationType.AUTO)
    	override val _dbId: Long? = null,
    	@Column(name = "first_name")
    	var info: String = ""
    ) : BaseEntity<Long>()
    m
    i
    a
    • 4
    • 6
  • k

    Konstantin Petrukhnov

    08/30/2019, 11:46 AM
    Every time I migrate to next Kotlin version, I have to spend many days fixing builds, code, etc in the project (every time I bump k/n version, my builds broke). Every time I migrate to next Kotlin version, somewhere during migration I start googling for better alternatives, that allow to share same performance critical code for iOS, desktop and backend platforms. Every time I actually found some new tool that could do similar things, but estimates shows that it would take at least twice more time (excluding learning time) to use new tool compared to Kotlin. Thank you very much for Kotlin, K/N and the ability to deliver solutions to multiple platforms in very short time!
    r
    c
    i
    • 4
    • 6
  • l

    LastExceed

    08/30/2019, 12:35 PM
    i've noticed that with asynchronous programming i quickly end up making almost every function in my code
    suspend
    . is that a sign of bad code or is this normal? i've read somewhere that at least in C# "async everything" is pretty common but im not sure if that applies to kotlin as well
    l
    s
    g
    • 4
    • 5
  • e

    Eugen Martynov

    08/30/2019, 1:12 PM
    Sealed with Enum (https://antonioleiva.com/sealed-classes-kotlin/)
    d
    • 2
    • 1
  • e

    Eugen Martynov

    08/30/2019, 1:13 PM
    Would you go to
    sealed class Operation(val value: Int) { class Add()...class Divide()}
    or
    class Operation(val type:Type, val value: Int)
    where
    Type
    is enum?
    s
    m
    • 3
    • 29
  • h

    halirutan

    08/30/2019, 3:10 PM
    Tomorrow the Kotlin Heroes Practice 2 is taking place. Is someone aware of boilerplate code that let's you quickly test the
    main
    fun with the examples provided in the problems?
    p
    • 2
    • 5
  • n

    Nikky

    08/30/2019, 7:50 PM
    This property is marked as @Transient and therefore must have an initializing expression
    seems like this is no longer valid?
    @Transient
    lateinit var rootDir: File
    this seems to only be a error on 1.3.50, worked fine on 1.3.41
    c
    s
    • 3
    • 6
  • s

    Shawn

    08/30/2019, 11:41 PM
    is there any kind of multi-key
    associate { }
    function that I’m missing? I’m trying to build a map and have multiple keys associated with the objects I’m iterating over - currently I’ve got something like this:
    entries.flatMap { entry ->
          (entry.aliases + entry.name).map { it to entry }
    }.toMap()
    which probably isn’t the most efficient approach 😬
    u
    k
    • 3
    • 5
  • m

    Mehdi

    08/31/2019, 8:48 AM
    What is the difference between using Coroutine and KotlinRx? or we could use them both?
    g
    • 2
    • 8
  • k

    Kroppeb

    08/31/2019, 3:56 PM
    How can I make a simple tcp socket listener? The following python code does the job
    python
    import socket
    
    IP = "127.0.0.1"
    PORT = 25565
    
    sock = socket.socket(socket.AF_INET, # Internet
                         socket.SOCK_STREAM)
    sock.bind((IP, PORT))
    sock.listen(1)
    conn, addr = sock.accept()
    try:
    	while True:
    		data = conn.recv(1024)
    		if not data: break
    		print(*(hex(i)[2:].rjust(2,'0') for i in data))
    finally:
    	conn.close()
    but I can't seem to find an easy solution in kotlin
    d
    • 2
    • 2
  • k

    Kroppeb

    08/31/2019, 9:53 PM
    I have the following code, and I need a lot of similar looking ones. What is the easiest way to generate these?
    class Handshake (val ProtocolVersion : Int,
    				 val ServerAdress : String,
    				 val port : UShort,
    				 val NextState : Int): Packet{
    
    
    
    	override suspend fun sendData(channel: WriteByteChannel) {
    		channel.write {
    			varInt(ProtocolVersion)
    			string(ServerAdress)
    			uShort(port)
    			varInt(NextState)
    		}
    	}
    
    	
    
    
    	companion object {
    		fun parse(channel: ReadByteChannel) = Handshake(
    			ProtocolVersion = channel.readVarInt(),
    			ServerAdress = channel.readString(255),
    			port = channel.readUShort(),
    			NextState = channel.readVarInt()
    		)
    	}
    }
    d
    • 2
    • 2
  • l

    LastExceed

    09/01/2019, 7:38 AM
    class Human(val name: String, age: Int) {
        var age = age
            private set
        
        fun birthday() {
            //party hard
            age++
        }
    }
    can this be simplified somehow or is it good as is?
    p
    d
    • 3
    • 9
  • k

    Kroppeb

    09/01/2019, 10:41 AM
    I have the following class:
    class enum<T:Types<R>, R>(Name: String) : Types<R>(Name)
    but is it possible to have the following
    val p = enum<varInt>("NextState"))
    
    // instead of
    
    val p = enum<varInt, Int>("NextState"))
    
    // varInt
    class varInt(Name: String) : Types<Int>(Name)
    w
    a
    • 3
    • 5
  • r

    rrader

    09/01/2019, 4:49 PM
    What is equivalent of Java
    "X-Secret"::equalsIgnoreCase
    ?
    l
    s
    • 3
    • 5
  • e

    Eugen Martynov

    09/02/2019, 5:42 AM
    I see that my team mates are using
    lateinit var
    for things that should be downloaded first. Is it good practice? (I don’t like it)
    m
    p
    +2
    • 5
    • 13
  • l

    LastExceed

    09/02/2019, 6:24 AM
    fun main() {
        val x = Thing(42)
        when(x) {
            Thing(42) -> {
                println("foo")
            }
            else -> {
                println("bar")
            }
        }
    }
    
    inline class Thing(val value: Int)
    the output is
    foo
    IntelliJ suggests inlining
    x
    , like so:
    fun main() {
        when(val x = Thing(42)) {
            Thing(42) -> {
                println("foo")
            }
            else -> {
                println("bar")
            }
        }
    }
    
    inline class Thing(val value: Int)
    however now it outputs
    bar
    . why is that?
    k
    e
    +2
    • 5
    • 5
  • y

    yen

    09/02/2019, 12:46 PM
    Are there any good Kotlin/Java loggers that doesn't rely on reflection?
    r
    u
    +4
    • 7
    • 12
  • b

    Bernhard

    09/02/2019, 2:04 PM
    basically:
    val list: List<Pair<String, String>> = listOf(
                "a" to null,
                "b" to "hi"
            )
                .filter {it.second != null}
    a
    l
    k
    • 4
    • 15
  • u

    ushort

    09/02/2019, 3:49 PM
    Why is kotlin dsl for gradle so buggy o.o Created a fresh gradle project with kotlin dsl enabled aand opening thhe file build made intellij freeze and full of errors but still built fine
    🤷‍♂️ 1
    s
    m
    • 3
    • 2
  • n

    ndv

    09/02/2019, 4:25 PM
    Hello everyone. Experiencing an odd problem since upgrading to Kotlin 1.3.50 in a maven project Basically, I have a folder containing .otf font files which gets copied to a different folder during runtime. The code looks as follows:
    private fun copyFonts () {
            val fontsFolder = File(javaClass.getResource("../../fonts").file)
            val fontsOutput = File(options.fontOutputLocation)
            if (!fontsOutput.exists()) fontsOutput.mkdir()
            fontsFolder.copyRecursively(fontsOutput, overwrite = true) { file, exception ->
                throw IllegalStateException("Could not copy file ${file.absolutePath}. ${exception.message}")
            }
        }
    However, the .otf files seem to get corrupted somehow during the copy. I've tried manually converting each file to a byte array and creating files manually, same problem. In a nutshell, the files in the original /fonts folder are around 90kB, once they've been copied over they are about 150kB and LaTeX no longer recognizes the file. If I manually copy the original font files over to the output folder, LaTeX compilation goes back to working normally. I just recently updated from Kotlin 1.3.31 to 1.3.50 - which is when the problem started. Any suggestions? Thank you! EDIT: Just tried by calling
    robocopy
    from inside Kotlin - same problem. However, calling robocopy from powershell copies the files correctly Also: my .otf files seem to be the only ones affected by this.
    • 1
    • 2
  • p

    pp.amorim

    09/02/2019, 6:01 PM
    It's wrapped around a
    string?.let { //... }
    , if I remove this I get this warning (waiting upload...)
    b
    • 2
    • 1
  • p

    pp.amorim

    09/02/2019, 6:01 PM
    If I remove I get this error
    w
    s
    • 3
    • 3
  • a

    Alessandro Tagliapietra

    09/02/2019, 7:36 PM
    Someone knows how to convert this java snippet in kotlin? https://kafka.apache.org/23/javadoc/org/apache/kafka/streams/kstream/KStream.html#process-org.apache.kafka.streams.processor.ProcessorSupplier-java.lang.String...- Specifically the part when it does
    return new Processor() {...
    ?
    n
    m
    • 3
    • 4
  • j

    josephivie

    09/02/2019, 9:42 PM
    I'm working on a new way to build projects using vanilla Kotlin files importing this library, with the hopes that one day it could replace Gradle. I'd really like some input from people on this. https://github.com/UnknownJoe796/kbuild
    k
    m
    m
    • 4
    • 5
  • o

    Oleh Ponomarenko

    09/03/2019, 12:55 PM
    Hello! How can I cast and run a method in Kotlin as example in Java I need to do this:
    it as ImageButton
     it.rotateSmoothly()
    Like this:
    (ImageButton) it.rotateSmoothly();
    m
    p
    e
    • 4
    • 5
  • p

    pawel.rybicki

    09/03/2019, 3:55 PM
    I got crash on prod and had to use 'allowedUrls?.forEach' even tho IDE tells me it is not necessary
    m
    e
    +3
    • 6
    • 11
Powered by Linen
Title
p

pawel.rybicki

09/03/2019, 3:55 PM
I got crash on prod and had to use 'allowedUrls?.forEach' even tho IDE tells me it is not necessary
m

Marko Mitic

09/03/2019, 3:56 PM
If superclass constructor is calling
setText
, allowedUrls won't be initialized in time
👍 5
👌 3
e

Eugen Martynov

09/03/2019, 3:57 PM
Actually good guess!
w

wasyl

09/03/2019, 3:58 PM
Yep, nice catch!
c

Casey Brooks

09/03/2019, 3:58 PM
Yup, that's what going on. From the source of
TextView
base class:
public TextView(
            Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        // TextView is important by default, unless app developer overrode attribute.
        if (getImportantForAutofill() == IMPORTANT_FOR_AUTOFILL_AUTO) {
            setImportantForAutofill(IMPORTANT_FOR_AUTOFILL_YES);
        }

        setTextInternal(""); <-- THIS IS THE CRASH
s

streetsofboston

09/03/2019, 3:59 PM
And this is why folks complain about the poor API design (and implementation) of the Android Framework…..
p

pawel.rybicki

09/03/2019, 4:01 PM
Oh holy cow I would never expect that! I wonder why did this happen randomly on some textview? This is in recyclerview and worked for several days just fine, displaying bunch of textviews
Anyone?
w

wasyl

09/03/2019, 4:12 PM
I don’t think the problem is that
setTextInternal
, but there’s another
setText
call in the constructor. But maybe it’s only there on certain Android versions?
p

pawel.rybicki

09/03/2019, 4:22 PM
Nope it was for single user for different OSes, I could not spot the difference in content for this user but I guess smth must be differently there
c

Casey Brooks

09/03/2019, 4:31 PM
With that
?.let
call, it might be that the initial
textViewMessage
is null in the majority of cases
p

pawel.rybicki

09/03/2019, 4:35 PM
Then the crashing code would not execute at all
View count: 1