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
getting-started
  • c

    Chris Cordero

    04/12/2020, 10:36 PM
    This second thought seems to be well supported, since there is a built-in method that facilitates it: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/to-map.html
    r
    r
    • 3
    • 4
  • j

    Jehandad Kamal

    04/13/2020, 6:41 AM
    Hi guys, I tried getting started on kotlin native and dont understand whether or not we can use exceptions. What ever I do cannot import IllegalArgumentException in native code. Why is that? Tried searching but didn;t find anywhere stating that this shoudn;t work
    a
    • 2
    • 2
  • u

    Uberunix

    04/13/2020, 5:05 PM
    Hello! I'm beginning my first Kotlin course and I'm confused about the creation of objects. The instructor has created them in two different ways Method 1:
    val myNewObject = NewObject(x,y,z)
    Method 2:
    val myNewObject: NewOject = NewObject(x,y,z)
    Is there a practical reason that he declared the type of "myNewObject" in certain cases? It seems unnecessary.
    a
    • 2
    • 4
  • e

    Enock Kalya

    04/14/2020, 6:00 AM
    Hello everyone, can someone point to useful resources for kotlin like a book or practice exercise I can get my hands dirty with.
    :google: 4
    m
    m
    +2
    • 5
    • 5
  • s

    Sanket Mehta

    04/14/2020, 10:26 AM
    fun testWhenSyntaxDataProvider(): Array<Array<Any?>> {
            return arrayOf(
                arrayOf(null, null, 10),
                arrayOf(1, null, 10),
                arrayOf(null, 2, 20),
                arrayOf(10, 20, 30)
            )
        }
    The above function is throwing below exception:
    Kotlin: Type inference failed. Expected type mismatch: inferred type is Array<Array<out Any?>> but Array<Array<Any?>> was expected
    How can I typecast Int to Any?
    d
    • 2
    • 3
  • i

    iseki

    04/15/2020, 12:29 AM
    Hi, I want to know the best practices to writing a codegen. KAPT only support JVM and it can't modify code. Compiler plugin is so difficult to write and looks it's only works on IR level? And both them make IDE hardly to use. So... What's the best practices? Thank you...
    r
    • 2
    • 1
  • c

    crummy

    04/15/2020, 10:53 AM
    historically it was common to run the oracle JDK in production. Nowadays I think a lot of folks just run openJDK everywhere.
    m
    d
    • 3
    • 17
  • p

    Pedro González

    04/15/2020, 8:48 PM
    I'm used to working with tornadofx for java 8 but a newbie with the new way javafx is decoupled, and also starting with gradle
    s
    • 2
    • 3
  • k

    Keith

    04/16/2020, 8:06 PM
    val alsoEmpty = listOf<String>()
    
    alsoEmpty.add("funny face")
    error: unresolved reference: add
    alsoEmpty.add("funny face")
    a
    i
    • 3
    • 4
  • a

    Ananiya

    04/17/2020, 4:25 PM
    how do i correct this code i was trying to print "very strong" when the password is very strong but it prints both "very strong" and "strong" and "need improvement" if the password is weak it works fine
    k
    c
    • 3
    • 4
  • s

    Slawomir Ziolkowski

    04/18/2020, 11:18 AM
    Hi, I'm new to Kotlin. Amazing language but sometimes it confuses me a lot 🙂 Maybe someone could help me there:
    fun main(args: Array<String>) {
        val firstList = listOf<User>(
                User(name="P-0"), User(name="P-0"), User(name="P-0"),
                User(name="P-2"), User(name="P-2"), User(name="P-2"), User(name="P-2")
        )
        val secondList = listOf<User>(User(name="P-2"))
        print(firstList.minus(secondList))
    }
    
    data class User(val name: String)
    I expect that only one P-2 element will be not in the result, but the result looks like this: [User(name=P-0), User(name=P-0), User(name=P-0)]
    d
    m
    +2
    • 5
    • 9
  • r

    Raymond Gao

    04/18/2020, 5:44 PM
    Hi I'm playing around with some serialization using reflection. I would like to be able to serialize some simple classes into JSONObjects in the following way
    val foo : Foo = Foo()
    var jobj : JSONObject = serialize(foo)
    var foo2 : Foo = construct(jobj, Foo::class)
    The methods serialize and construct will inspect the object using reflection, find any fields that match a set of constraints and add their values to a json object or send them into the appropriate constructor of
    Foo
    to create a new object It works until I run into Generics
    class Foo(val map : Map<String, Int>)
    {
    ...
    }
    I'm having some difficulty getting the type parameters passed into
    Map
    at runtime. My friend has told me about the concept of type erasure. It seems that kotlin throws away these arguments at runtime. I have resorted to annotating the field with the appropriate types for now, but it causes some ugly duplication of information already typed down.
    class Foo(@param:GenericsHint([String::class, Int::class]) val map : Map<String, Int>)
    Does anyone have any ideas on how I can get around this problem? Thanks 🙂
    a
    j
    • 3
    • 3
  • f

    fmcauley

    04/19/2020, 4:55 PM
    Disclaimer: not sure if this the correct channel for my question... I have an older android project with numerous dependencies that I, as of yet, have been able to get past Gradle 3.3. When I attempt to build a new class using Kotlin and Android Studio offers to update my Gradle dependencies I get an error that I need Gradle version 4.9 or higher. So, is there a way to add Kotlin support to my project independent of Gradle? Or is there another workaround? I would love to develop with Kotlin as I work on cleaning up the codes dependencies and navigate to newer versions of Android Studio and Gradle.
    s
    m
    • 3
    • 3
  • c

    Chris Cordero

    04/20/2020, 1:15 PM
    Are Kotlin `MutableList`s implemented like a linked list under the hood? Can I pop/append from both ends or from the middle cheaply? Or is this an expensive calculation
    d
    d
    • 3
    • 12
  • m

    Madalin Valceleanu

    04/21/2020, 7:53 AM
    📚 Android Sample App using modular, clean, scalable, testable Architecture written in Kotlin that presents modern approach to Android application development, latest tech-stack and best practices. Application is based, apply and strictly complies with each of the following 5 points: • A single-activity architecture, using the Navigation component to manage fragment operations. • Android architecture components, part of Android Jetpack give to project a robust design, testable and maintainable. • Pattern Model-View-ViewModel (MVVM) facilitating separation of development of the graphical user interface. • S.O.L.I.D design principles intended to make software designs more understandable, flexible and maintainable. • Modular app architecture allows being developed features in isolation, independently from other features. Project link: https://github.com/VMadalin/kotlin-sample-app
    m
    v
    • 3
    • 2
  • i

    iseki

    04/21/2020, 4:14 PM
    In Kotlin. I need a lambda:
    (T)->Unit
    `<T: Any`> but allow null when T is nullable type... How to do that? Thank you
    s
    f
    +2
    • 5
    • 10
  • d

    Daniel Lukic

    04/22/2020, 12:01 PM
    could someone point me to where i can ask some - most probably stupid - ktor client related beginner questions? 😳 🙈 like.. how to read a json response if 200 and handle non-200 otherwise explicitly.. 🤔 right now it seems this should be handled via try catch.. which seems a bit weird.. but maybe it isn't.. 🤔
    r
    a
    • 3
    • 3
  • a

    Alexander Finn

    04/22/2020, 4:29 PM
    I have a newbie generics question here. I'm using a library (KMongo) that exposes an inline method with reified parameter:
    inline fun <reified TDocument : Any> getCollection(
        collectionName: String = KMongoUtil.defaultCollectionName(TDocument::class)
    ): CoroutineCollection<TDocument>
    In my code I want to create an interface with a default method that would return a collection for specified type:
    interface MongoDBRepository<T: Any> {
    
        val client: CoroutineClient
    
        fun collection(): CoroutineCollection<T> {
            return client.getDatabase(accountId).getCollection<T>()
        }
    
    }
    However, the compiler complains that 'T' can not be used as a reified type parameter here. And defining a reified type parameter would require me to change collection() to an inline function which is something I can not do in an interface. Any thoughts on how to change the code to make an interface functional? Or am I doing something completely wrong?
    g
    d
    • 3
    • 3
  • m

    Maciek

    04/22/2020, 4:52 PM
    is there a way to do multiple class generic constraints and interface delegation? Because of delegation it doesn't compile 🤔
    Untitled
    s
    • 2
    • 6
  • k

    Kenneth

    04/23/2020, 8:52 AM
    I have a java class without a constructor that I want to initialize with a value, is there a shortcut to do this in kotlin or do I have to initialize and use the setter?
    d
    • 2
    • 4
  • a

    Ananiya

    04/23/2020, 11:57 AM
    i was trying to change the value externally here is my code
    class SettingMyValue{           var setLength = 9 }
    and from external kt file i put this code
    SettingMyValue().setLength = 7
    to reassign the value of
    setLength
    externally but it return 9 but all i want was to print the reassigned value (7) and if there is no external change returns 9
    k
    • 2
    • 4
  • k

    Kenneth

    04/23/2020, 2:28 PM
    Is using
    !!
    something that should be avoided?
    :yes: 13
    🇳🇴 2
    e
    s
    +3
    • 6
    • 7
  • g

    Gilberto Diaz

    04/23/2020, 4:35 PM
    it is a way to get the parameter’s name?
    m
    • 2
    • 2
  • e

    Erik Dreyer

    04/24/2020, 8:29 PM
    What’s the correct way to convert an
    Array<Int?>
    to
    Array<Int>
    d
    • 2
    • 2
  • g

    Gilberto Diaz

    04/25/2020, 2:29 AM
    I want to make sure I understand the docs. Here says that Map preserves the order of elements insertion. What I understand is that when I use
    mapOf(…)
    or
    mutableMapOf(…)
    , the order in which elements are inserted are preserved. Is that a correct statement?
    k
    • 2
    • 2
  • j

    Joshua

    04/25/2020, 1:30 PM
    So I changed the parent's layout from
    layout
    to
    androidx.drawerlayout.widget.DrawerLayout
    and now I get the following error...
    AAPT: error: 'ferm.jonny.willow.models.ToolbarViewConfig' is incompatible with attribute type (attr) enum [linear=0, radial=1, sweep=2].
    Any clue what this is about?
    • 1
    • 1
  • k

    keishi kubo

    04/25/2020, 6:14 PM
    Does kotlin has string lietral type as typescript? Such as type Role = “admin” | “user” | “root”
    r
    • 2
    • 2
  • p

    PK

    04/26/2020, 5:37 AM
    apologies in advance if this is not the correct place to ask this question
    k
    • 2
    • 5
  • c

    Chetan Sachdeva

    04/27/2020, 1:13 PM
    Hello all! What is the way to setup CI/CD for a kotlin multiplatform project?
    m
    • 2
    • 4
  • a

    Alex Wilson

    04/28/2020, 4:08 PM
    I am working through The Joy of Kotlin and came to this earlier today. Pages 61 and 62.
    fun compose(f: (Int) -> Int, g: (Int) -> Int): (Int) -> Int = { f(g(it)) }
    I understand this example. The next step was to make the compose function polymorphic by using type parameters. I'm having a hard time making sense of this. Since they are all the same type of Int, I thought it would be just this:
    fun <T> compose23Example(f: (T) -> T, g: (T) -> T): (T) -> T = { f(g(it)) }
    The solution however is this:
    fun <T, U, V> compose(f: (U) -> V, g: (T) -> U): (T) -> V = { f(g(it)) }
    I've been looking at it and am having difficulty understanding exactly what I'm looking at. Can anyone help?
    d
    m
    c
    • 4
    • 5
Powered by Linen
Title
a

Alex Wilson

04/28/2020, 4:08 PM
I am working through The Joy of Kotlin and came to this earlier today. Pages 61 and 62.
fun compose(f: (Int) -> Int, g: (Int) -> Int): (Int) -> Int = { f(g(it)) }
I understand this example. The next step was to make the compose function polymorphic by using type parameters. I'm having a hard time making sense of this. Since they are all the same type of Int, I thought it would be just this:
fun <T> compose23Example(f: (T) -> T, g: (T) -> T): (T) -> T = { f(g(it)) }
The solution however is this:
fun <T, U, V> compose(f: (U) -> V, g: (T) -> U): (T) -> V = { f(g(it)) }
I've been looking at it and am having difficulty understanding exactly what I'm looking at. Can anyone help?
d

Dominik wuttke

04/28/2020, 4:14 PM
Your example would mean, that you can only enter 1 type, when you have an Int everything had to be an Int. What really happen is, that you can enter any type for the function
g()
and return any type you want. You can for example have an`Int` as variable for
g()
and return a
String
. The returntype of
g()
is the type which
f()
needs.
f()
can now return any type you want. Your case is only correct when everything has the same type of variable, which is not always the case.
m

molikuner

04/28/2020, 4:16 PM
Theoretically your solution would work as well, as long as you only compose functions with the same type. So you could use your function to do the same thing as the example does with Int, but the actual “solution” is way more agile, as you can use multiple types there. Let me give an example:
val myWeiredLength: (String) -> Int = compose<String, Int, Int>(f = { it + 1 }, g = { it.length })
That wouldn’t be possible with your solution.
c

Casey Brooks

04/28/2020, 4:18 PM
Your solution is technically valid, but it only works for composing functions of a single type. There is no way for it to convert from one type to another. This example might help clear up the differences https://pl.kotl.in/fXK4lgQz4
a

Alex Wilson

04/28/2020, 4:40 PM
Thank you! I can tell that I'm on the verge of understanding it, having moments of clarity, just waiting for the final picture. I'll chew on the examples you've all given. I appreciate you taking the time to respond!
👍 2
This make any sense?
fun <T, U, V> compose(f: (U) -> V, g: (T) -> U): (T) -> V = { f(g(it)) }
A function called "compose" that returns a function that satisfies the signature
(T) -> V
. We're setting that return to a lambda of
f(g(it))
. Our method signature takes two parameters:
f:
a function with a parameter of type
U
that transforms into a result into type
V
g:
a function with a parameter of type
T
that transforms into a result into into type
U
V
represents
f(g(it))
T
represents
it
g
transforms
T
to
U
f
transforms
U
to
V
👍🏻 1
View count: 2