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

    nfrankel

    01/10/2019, 12:47 PM
    anyone knows how to skip dokka generation with the maven plugin? just like i’d skip tests with
    mvn package -DskipTests
    trying
    mvn package -Dskip
    without success 😞
    k
    • 2
    • 4
  • j

    jeggy

    01/10/2019, 3:23 PM
    Is it possible in some way to get access to the outer class properties when creating an extension function on an inner class?
    class Outer(var value: String = "") {
        inner class Inner {
            var id = 0
            val str: String get() = value + id
        }
    }
    fun main(args: Array<String>) {
        fun Outer.Inner.update() = also { value = "Hello World" } // I don't have access to `value` here :(
        println(Outer().Inner().update().str)
    }
    a
    d
    • 3
    • 3
  • d

    Dalinar

    01/10/2019, 4:05 PM
    if I have a top-level
    fun
    how can I make a static import for it in Java?
    s
    f
    a
    • 4
    • 32
  • k

    kz

    01/10/2019, 4:37 PM
    I definitely agree with Jake but as a thought experiment, would performance really suffer if everything was inlined? If a lot of things were inlined you would definitely get instruction cache misses for function calls. But if all function calls were inlined? The binary would definitely be prohibitively large.
    k
    • 2
    • 2
  • k

    karelpeeters

    01/10/2019, 7:11 PM
    Makes sense, I was just making sure 😒imple_smile:
    a
    • 2
    • 2
  • a

    amanda.hinchman-dominguez

    01/10/2019, 7:37 PM
    @karelpeeters I guess it doesn't crash but at this point in the project "working" is... subjective hahaha
    k
    • 2
    • 6
  • x

    xenoterracide

    01/10/2019, 8:19 PM
    can I use a java annotation preprocessor with kotlin? like one that generates source? specifically thinking of the immutables library. https://immutables.github.io
    c
    • 2
    • 1
  • s

    sean

    01/10/2019, 9:36 PM
    Hi everyone! Has anyone distributed a kotlin command line app before? Ideally I'd like to distribute a self contained binary, I know using gradle + application plugin + shadow plugin you can distribute a single jar with a platform specific wrapper (and just depend on java being installed where it is run). Capsule seems like it can do one better and make it all one file but it doesn't seem actively maintained http://www.capsule.io/
    c
    n
    p
    • 4
    • 9
  • x

    xenoterracide

    01/10/2019, 10:46 PM
    when I check constructors
    Expected size:<2> but was:<1> in:
        <[fun <init>(kotlin.String, kotlin.String, kotlin.String, java.time.Instant, kotlin.String, kotlin.String): com.potrero.ph.emr.entity.Emr]>
            at com.potrero.ph.emr.entity.EmrTest.new(EmrTest.kt:12)
    k
    • 2
    • 2
  • p

    paxi

    01/11/2019, 2:30 AM
    Hi, guys. I'm working on an android app, and upon decompiling Kotlin code I stumbled upon issue like this - https://twitter.com/chibatching/status/1046301000443736065 Is this a code smell that I'm doing something wrong in app (Kotlin) code, or just decompiler having its own issues? The bytecode on its own seems ok, no large bytecode files were generated. This happens on a simple
    runBlocking { var a = 1; var b = 2; a + b; }
    piece of code. I understand this is https://youtrack.jetbrains.com/issue/KT-28007, but must I include
    -din=0
    part?
    k
    g
    • 3
    • 3
  • b

    Bernhard

    01/11/2019, 12:29 PM
    hi guys, anything that I have to watch out for when changing vms from 8 to 11?
    g
    • 2
    • 1
  • n

    nickk

    01/11/2019, 1:40 PM
    If I ask for functional-language-style macros in Kotlin (like LISP , Elixir etc), I would currently be out of luck, right?
    n
    s
    +3
    • 6
    • 29
  • b

    Bernhard

    01/11/2019, 3:57 PM
    as in:
    listOfObjects
        .filter { it.field != null }
        .map { it.field.method() }
    t
    h
    +3
    • 6
    • 32
  • s

    Shawn

    01/11/2019, 7:41 PM
    Nope! But there is a :youtrack: open, as well as a KEEP. You can vote on it if it’s something you want to see in the language. https://youtrack.jetbrains.com/issue/KT-14663
    ➕ 1
    • 1
    • 1
  • r

    robstoll

    01/11/2019, 8:03 PM
    Which one would you prefer:
    foo<Int, String>(1, 2) { "result: $it" }
    foo(1, 2)<String>{ "result: $it" }
    The first one has less surprises but is more verbose than the second. Thoughts?
    k
    d
    +2
    • 5
    • 6
  • j

    Jainil Patel

    01/12/2019, 2:16 AM
    Hi
    👋 4
    d
    t
    • 3
    • 2
  • j

    jmfayard

    01/12/2019, 10:36 AM
    Is there any reason why measureTimeMillis { .. } is missing
    contract {
            callsInPlace(block, InvocationKind.EXACTLY_ONCE)
        }
    s
    g
    • 3
    • 2
  • y

    yodgor777

    01/12/2019, 2:35 PM
    and gist
    s
    c
    • 3
    • 2
  • s

    Slackbot

    01/12/2019, 3:50 PM
    This message was deleted.
    s
    c
    • 3
    • 4
  • h

    hmole

    01/12/2019, 6:19 PM
    Is compiling both java and kotlin sources in a single module still a problem? By problem I mean it compiles slower than it supposed to. Can't google related issue.
    e
    c
    • 3
    • 2
  • v

    Vishnu Haridas

    01/12/2019, 8:41 PM
    Note: Recently in my project I introduced a bug. I took the literal meaning of the word
    also
    when I wrote the code 😄 So I thought of sharing it so that others will find the fun and enjoy it.
    What_will_the_output_.kt
    😒imple_smile: 1
    c
    • 2
    • 1
  • c

    cbruegg

    01/13/2019, 10:54 AM
    I'd recommend benchmarking it, seems like autoboxing-removal itself is not implemented: https://stackoverflow.com/a/21954389/1502352 But maybe escape analysis can help in some cases, which should allow allocation on the stack instead of on the heap. I don't know for sure though.
    p
    • 2
    • 2
  • d

    Dico

    01/13/2019, 9:00 PM
    fun maxSubarraySum(list: List<Int>, n: Int): Int? {
        if (list.isEmpty()) return null
        return (0..list.size - n).map { i -> list.subList(i, i + n).sum() }.max()
    }
    👍 3
    i
    • 2
    • 1
  • a

    Alan Evans

    01/13/2019, 9:54 PM
    You could do it in linear time, using fold, both more efficient, and more Kotlinly!:
    fun List<Int>.maxSubListSum(n: Int) =
        take(n)
            .sum()
            .let { sum ->
                drop(n)
                    .foldIndexed(sum to sum) { i, (sum, max), next ->
                        (sum + next - this[i]).let {
                            it to if (it > max) it else max
                        }
                    }.second
            }
    (Sorry for no thread).
    👍 1
    d
    l
    i
    • 4
    • 26
  • r

    rnett

    01/14/2019, 2:41 AM
    I'm trying to instantiate a java class
    class Builder<T extends Builder<T>>
    . In java, you just use
    new SpaceToBatchLayer.Builder()
    , however, Kotlin forces you to specify the type argument. Is there a way around this for interop w/ java?
    s
    c
    • 3
    • 3
  • a

    Alexjok

    01/14/2019, 7:49 AM
    Hello, can anyone explain channels are thread safe structure? When is a global variable
    r
    • 2
    • 3
  • t

    thana

    01/14/2019, 11:15 AM
    i am observing there is a special tratement for class fields of type
    Long
    when they are initialized with
    0
    but i cannot find documentation for this behavior. furthermore it is not applied when the code is compiled in to javascript. any help on this?
    c
    d
    • 3
    • 26
  • h

    hudsonb

    01/14/2019, 7:25 PM
    Plus
    do
    is a Java keyword
    s
    d
    h
    • 4
    • 3
  • d

    Dico

    01/14/2019, 11:43 PM
    On the interface, declare the default value as
    Consumer {}
    👍 1
    x
    • 2
    • 2
  • x

    xenoterracide

    01/15/2019, 2:58 PM
    val bis = from.buffered()
    
            var b : ByteArray = byteArrayOf()
            while ( ( bis.read(b) ) != -1 ) {
    
            }
    is there a better way to read in bytes in kotlin (yes the file is binary)
    h
    a
    p
    • 4
    • 26
Powered by Linen
Title
x

xenoterracide

01/15/2019, 2:58 PM
val bis = from.buffered()

        var b : ByteArray = byteArrayOf()
        while ( ( bis.read(b) ) != -1 ) {

        }
is there a better way to read in bytes in kotlin (yes the file is binary)
h

hho

01/15/2019, 3:00 PM
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/read-bytes.html ?
x

xenoterracide

01/15/2019, 3:01 PM
can't use that, this can apparently be up to 256G
a

Alan Evans

01/15/2019, 3:04 PM
you can't even do it that way really, you will need the result of
read
(and a capacity on the byte array)
x

xenoterracide

01/15/2019, 3:11 PM
@Alan Evans yeah...
var bytes = ByteArray(72)
        var read = 0
        while ( ( read = bis.read(bytes) ) != -1 ) {
            for (byte in bytes) {
                addByte( byte )
            }
        }
kotlin doesn't like the assignment there
a

Alan Evans

01/15/2019, 3:12 PM
yeah 😞
x

xenoterracide

01/15/2019, 3:12 PM
is this some weird edge case where I'm going to have to write some of it in java
a

Alan Evans

01/15/2019, 3:13 PM
no no, but it won't look as clean that's all
val b = ByteArray(4096)
        do {
            val read = bis.read(b, 0, b.size)
            if (read == -1) break
            // you got "read" bytes in buffer

        } while (true)
a
do while
is the cleanest way I know of
but the
while(true)
is icky
x

xenoterracide

01/15/2019, 3:17 PM
yeah... this is a slurp though right, puts everything in the array, which I'm thinking I don't actually want... hmmm.... I think this is enough for me to work with though. Thanks
a

Alan Evans

01/15/2019, 3:18 PM
But you can hide it away:
fun InputStream.readInBlocks(blockSize: Int = 4096, function: (ByteArray, Int) -> Unit) {
    val buffer = ByteArray(blockSize)
    do {
        val count = read(buffer, 0, blockSize)
        if (count == -1) break
        function(buffer, count)
    } while (true)
}
Usage:
bis.readInBlocks { buffer, count ->
            // you got "count" bytes in buffer
        }
👍 1
How do you mean "puts everything in the array"?
x

xenoterracide

01/15/2019, 3:20 PM
reads the stream until the stream is empty
I guess it doesn't, that wouldn't make sense
a

Alan Evans

01/15/2019, 3:21 PM
ok, and oh and you might actually want to use
inline fun
as that would save a lot of function calls over 256GB of small blocks.
Yes the array gets reused, it's only ever 4096 bytes if that was your confusion.
x

xenoterracide

01/15/2019, 3:26 PM
my confusion is it's before 10am and java's io api... 😉 but yes... more caffeine
I don't do a lot of file reading, and just learning kotlin, so thanks 😄
@Alan Evans one last question about this code, the extension method could be used on any inputstream right? do you have any suggestions on code placement for extension methods?
a

Alan Evans

01/15/2019, 3:36 PM
Not particularly. I would just say apply same reasoning as any other function: Do you need to access it from multiple classes? then put somewhere they can all access it. If just for one place, you can put at the bottom of that file and keep
private fun
. Remember you can always move later, and I think it's best to keep visibility of anything, class, function or property, to the minimum you need.
p

pp.amorim

01/17/2019, 12:27 PM
Okio
x

xenoterracide

01/17/2019, 4:48 PM
?
https://stackoverflow.com/q/54229767/206466 hmm... same problem, am I doing something wrong in the loop?
@pp.amorim you have an example of how I might do this with okio? looking at the lib but find its immediate examples opaque for my use case
View count: 2