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

    Andrew Gazelka

    01/07/2019, 1:56 AM
    what is everyone's opinion on having private helper (extension) functions vs having nested helper functions
    d
    k
    • 3
    • 3
  • r

    rajkumar

    01/07/2019, 5:35 AM
    Does Kotlin/Native (say for iOS) creates - iOS binary or - the code that can be imported on XCode and then built into iOS binary or - both?
    m
    • 2
    • 1
  • k

    karelpeeters

    01/07/2019, 9:15 AM
    The
    -
    operator.
    t
    • 2
    • 1
  • a

    APXEOLOG

    01/07/2019, 1:41 PM
    Hello guys. I have a question about generics. I have following code:
    val properties = mutableListOf<Property>()
    
    inline fun <reified T : Property> getProperty(): T? {
        return properties.filter { it::class == T::class }.firstOrNull() as T?
    }
    I don't like this
    as T?
    part, but if i remove it i will receive error:
    Type inference failed. Required: T?, found: Property?
    Am i doing something wrong?
    g
    d
    • 3
    • 8
  • l

    LeoColman

    01/07/2019, 4:01 PM
    I do have a lot of experience with Kotlin, but I'm afraid that I'll flood them with too much information that seems trivial for me
    a
    h
    +3
    • 6
    • 14
  • d

    dewildte

    01/07/2019, 4:28 PM
    I got my team to use Kotlin by highlighting the inherent increase to code quality that using Kotlin brings. I also highlighted some OO design patterns that are built in constructs in the language itself. Plus I mentioned that it makes refactor work a lot easier. I think the fact that there is too many benefits to go over in a 30 min presentation is a convincing point in itself. The best of the best are using Kotlin.
    b
    l
    • 3
    • 9
  • a

    adam-mcneilly

    01/07/2019, 4:42 PM
    Is it possible to reference a delegated property from Java? I would normally write this line in Kotlin:
    var myString: String by SharedPrefsString(myPrefs)
    but I wanna use my SharedPrefsString type in Java, if possible.
    d
    • 2
    • 2
  • s

    Slackbot

    01/07/2019, 4:48 PM
    This message was deleted.
    k
    • 2
    • 1
  • k

    karelpeeters

    01/07/2019, 7:12 PM
    Just call
    hashcode()
    ? Can you give an example?
    l
    • 2
    • 18
  • x

    xenoterracide

    01/08/2019, 12:42 AM
    I think this should work, but
    Exception in thread "main" java.lang.NoSuchMethodException: com.potrero.Application.main([Ljava.lang.String;)
    	at java.base/java.lang.Class.getDeclaredMethod(Class.java:2476)
    	at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:47)
    	at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
    	at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
    	at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
    package com.potrero
    
    import org.apache.logging.log4j.LogManager
    import org.springframework.beans.factory.getBeanProvider
    import org.springframework.boot.autoconfigure.SpringBootApplication
    import org.springframework.boot.info.BuildProperties
    import org.springframework.boot.runApplication
    
    @SpringBootApplication
    open class Application
    
    fun main(args: Array<String>) {
        val ctx = runApplication<Application>(*args)
        ctx.getBeanProvider<BuildProperties>().ifAvailable {
            LogManager.getLogger(Application::class.java).info("Starting {}", it.artifact)
        }
    }
    shouldn’t this kotlin class work to start spring boot?
    s
    • 2
    • 1
  • m

    Marcin Wisniowski

    01/08/2019, 9:29 AM
    I get a 403 here
    s
    • 2
    • 1
  • d

    damian

    01/08/2019, 2:05 PM
    Any suggestions / guidance on how I might optimise this? The arrays contain ~600 elements and this is executed every 500ms to formulate this string which then gets written to a file. Cpu is averaging ~30%.
    fun SamplingEvent.DataEvent.SensorArrayValuesEvent.toSensorDataString(): String {
        var segment = ""
        for (i in 0..(sensorCount - 1)) {
            segment += "$timestampNanos,${sensorType[i]},${values0[i]},${values1[i]},${values2[i]},${values3[i]},${values4[i]},${values5[i]}\n"
        }
        return segment.dropLast(1)
    }
    My first instinct is to lift this out of extension function and use/reuse StringBuilder (with sufficient initial buffer) ?
    a
    • 2
    • 2
  • m

    mbonnin

    01/08/2019, 2:27 PM
    This prints
    first=1 (int)
    but I thought kotlin has no implicit conversions.
    p
    • 2
    • 2
  • m

    mbonnin

    01/08/2019, 2:29 PM
    This decompiles as
    List listOfDouble = CollectionsKt.listOf(1.0D);
          if (listOfDouble == null) {
             throw new TypeCastException("null cannot be cast to non-null type kotlin.collections.List<kotlin.Int>");
          } else {
             int first = ((Number)listOfDouble.get(0)).intValue();
             System.out.println("first=" + first + " (" + Integer.TYPE.getName() + ')');
          }
    p
    d
    • 3
    • 9
  • r

    Richard Green

    01/08/2019, 2:40 PM
    A lot of the embedded examples here : https://blog.jetbrains.com/kotlin/2018/04/embedding-kotlin-playground/ no longer seem to work 😞
    r
    • 2
    • 1
  • a

    Andrew Gazelka

    01/08/2019, 5:40 PM
    Does variable initialization out of
    init{}
    occur after init and if so, is it a good practice if order matters to include it in
    init{}
    ? i.e.,
    class Logger(val logFile: Path)
    {
    
        val writer = Files.newBufferedWriter(logFile)
        
        init {
            if(!Files.exists(logFile))
            {
                Files.createFile(logFile)
            }
        }
    }
    d
    a
    +2
    • 5
    • 20
  • a

    Andrew Gazelka

    01/08/2019, 5:42 PM
    also is there a
    .field
    equivalent in Kotlin for constructors? I can't seem to find one, and it is really annoying to manually create the property definition...
    s
    • 2
    • 8
  • j

    Jannis

    01/08/2019, 7:26 PM
    Option also allows for much more control. Nullable types are nice but really don't offer anything in itself. Option implements typeclasses like Functor (enables .map), Monad (enables flatMap/bind), and lots more. This is functionality that nullable types can't provide and by using those typeclasses programs tend to become a lot simpler imo
    👍 2
    👎 3
    n
    b
    g
    • 4
    • 37
  • d

    DALDEI

    01/09/2019, 1:40 AM
    Q: Looking for what I expected Collection.singleOrNull() would do but doesn't, i.e. return single if 1 element, null if empty and throw if > 1 i.e. equivient to when( size ) { 0 -> null ; 1 -> first() ; 2 -> throw } Is there such a beast ? Its easy to write but maybe Im looking for the wrong words
    i
    • 2
    • 1
  • m

    myanmarking

    01/09/2019, 3:25 PM
    guys when i upgrate gradle plugin from 1.3.0 to 1.3.11, for some reason, dependencies in a module with API are not visible in another module that includes the previous one. any1 experimenting stuff like this ?
    n
    s
    • 3
    • 5
  • d

    dimsuz

    01/09/2019, 4:04 PM
    Is there a way to specify that I want to use boxed version of
    val
    ? I use DI framework and it finds primitive
    boolean
    here:
    class MyPresenter @Inject constructor(val field: Boolean)
    and fails to generate injector. One way is to use
    val field: java.lang.Boolean
    , but it feels a bit dirty and generates a warning
    h
    k
    +2
    • 5
    • 5
  • d

    davidkarlsen

    01/09/2019, 6:20 PM
    I had this Java code:
    @Bean
        @ConditionalOnProperty( prefix = "proxy", name = "enabled", havingValue = "true")
        public RestTemplateCustomizer restTemplateCustomizer() {
            return restTemplate -> {
                var proxy = new HttpHost(host, port, scheme);
                var httpClient = HttpClientBuilder.create().setRoutePlanner(new DefaultProxyRoutePlanner(proxy)).build();
                restTemplate.setRequestFactory( new HttpComponentsClientHttpRequestFactory(httpClient));
            };
        }
    where RestTemplateCustomizer is a functional interface. But I have trouble writing this in Kotlin
    s
    c
    • 3
    • 6
  • v

    ValV

    01/09/2019, 8:20 PM
    What is the better way to handle system path (
    /path/to/file
    ), than store it as a
    String
    ? Better way to split it later by directories (
    path
    ,
    to
    ,
    file
    )?
    h
    d
    +2
    • 5
    • 16
  • s

    snowe

    01/09/2019, 9:28 PM
    Anyone know why I might be getting
    Cannot access class 'kotlinx.serialization.KSerialLoader'. Check your module classpath for missing or conflicting dependencies
    ? I’ve followed the directions in the kotlinx readme.
    d
    • 2
    • 2
  • b

    Bernardo Ferrari

    01/10/2019, 1:58 AM
    How do I get clipboard access (read/write) on Kotlin, not Android, not AWT, not JavaFX, pure Kotlin for OS usage? I searched everywhere, the best answer so far has been to force users to install xclip, and call it from Runtime(), which is not a great solution.
    s
    e
    c
    • 4
    • 22
  • s

    serebit

    01/10/2019, 4:15 AM
    Is there any particular reason that
    class ReactMap : MutableMap<Long, MutableList<EmoteData>> by (mutableMapOf<Long, MutableList<EmoteData>>()
        .withDefault { mutableListOf<EmoteData>() })
    compiles fine, and
    class ReactMap : MutableMap<Long, MutableList<EmoteData>> by mutableMapOf()
    compiles fine, but
    class ReactMap : MutableMap<Long, MutableList<EmoteData>> by (mutableMapOf().withDefault { mutableListOf() })
    doesn't? Is it a bug in the compiler, or is it intentional?
    😕 1
    d
    • 2
    • 7
  • f

    fkrauthan

    01/10/2019, 5:45 AM
    Hey If I have a parameter defined as
    test: KClass<Any>
    how can I fix the problem that when for example passing in
    MyClass::class
    the type missmatch error?
    s
    s
    • 3
    • 4
  • a

    Andrew Gazelka

    01/10/2019, 10:58 AM
    is there any way to inherit super class default constructor values?
    open class A(val a: String, val b: String = "hello")
    
    class B(a: String, b: String, c: String) : A(a, b) {
    
    }
    in this scenario would it be possible to have
    b
    arg in class
    B
    have default value
    "hello"
    while being DRY?
    k
    c
    • 3
    • 5
  • a

    Andrew Gazelka

    01/10/2019, 11:00 AM
    also, any reason an arg of type
    Runnable
    can be called with
    () -> Unit
    but when the type is
    Runnable...
    ?,
    () -> Unit
    cannot be called?
    k
    • 2
    • 1
  • a

    Andrew Gazelka

    01/10/2019, 11:35 AM
    sorry for all these questions, but am I being dumb? pretty sure this should work with the
    out
    keyword
    k
    t
    • 3
    • 7
Powered by Linen
Title
a

Andrew Gazelka

01/10/2019, 11:35 AM
sorry for all these questions, but am I being dumb? pretty sure this should work with the
out
keyword
k

karelpeeters

01/10/2019, 11:58 AM
BackGroundAction.() -> Unit
is not a subtype of
PeriodicAction.() -> Unit
.
In fact it's the opposite way around.
It may be easier to see with
(Int) -> Unit
and
(Any) -> Unit
a

Andrew Gazelka

01/10/2019, 12:01 PM
oh, I see. I'm dumb
t

todd.ginsberg

01/10/2019, 2:19 PM
You aren’t dumb. This is how we learn things.
a

Andrew Gazelka

01/10/2019, 7:05 PM
btw @todd.ginsberg have to compliment you on your AoC repo. 🙂 helped me learn a lot of Kotlin fundamentals
t

todd.ginsberg

01/10/2019, 7:44 PM
Awesome! I’m so glad it helped!
View count: 1