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

    Colton Idle

    07/07/2021, 1:36 AM
    I want to write an extension function like so. How do I get around having to specify types?
    a
    • 2
    • 2
  • b

    Brian Dilley

    07/07/2021, 1:54 AM
    fun <T, E> ApiREsult<T, E>.myExtension() { }
    :thread-please: 1
    c
    c
    • 3
    • 2
  • s

    Stefan Oltmann

    07/07/2021, 10:46 AM
    I want to use Coroutines Flow to generate Thumbnails from images, but I'm not sure which Flow is the correct one to use. So my idea was to send images that need to be processed to a Channel and read from that with channelFlow() ... but since Channels are hot they seem to be a bad idea (after watching the KotlinConf2019 talk). I want to send a URL to a flow somehow and receive the ImageBitmap back. The first flow should read images from disk one after another, feed them to multiple coroutines that process thumbnails and send that back to the caller. How to do that?
    ✅ 1
    c
    c
    • 3
    • 29
  • a

    Ayfri

    07/07/2021, 2:53 PM
    Hi, what is the Kotlin version of
    JavaClass::new
    ?
    p
    • 2
    • 1
  • b

    Bradford Canonigo

    07/08/2021, 1:45 AM
    Hi all, thanks for the one who invited me here, I'm working on a KMM library project. I am having some compile errors on expect and actual keywords and says this feature should be enabled explicitly. Any thoughts on how to fix this?
    a
    • 2
    • 1
  • o

    oday

    07/08/2021, 9:41 AM
    I would like to append an element to an IntArray, how would I do it in something simpler than this?
    var result = intArrayOf(1, 2, 3, 4)
    
    val list = result.toMutableList()
    list.add(5)
    
    result = list.toIntArray
    a
    e
    +2
    • 5
    • 12
  • m

    Matias Reparaz

    07/08/2021, 8:39 PM
    Hi, I’m upgrading from 1.3.50 to 1.5.20 and I have this problem. This code now compiles
    class SomeClass<out T>(private val type: Class<T>, val getDefaultValue: () -> T) {
        constructor(type: Class<T>, default: T): this(type, {default})
    }
    but when I upgrade I have this error
    Kotlin: Overload resolution ambiguity: 
    public constructor SomeClass<out T>(type: Class<TypeVariable(T)>, getDefaultValue: () -> TypeVariable(T)) defined in SomeClass
    public constructor SomeClass<out T>(type: Class<TypeVariable(T)>, default: TypeVariable(T)) defined in SomeClass
    can someone explain me why this doesn’t work anymore and/or how can I rewrite it?
    e
    • 2
    • 4
  • c

    Colton Idle

    07/09/2021, 3:24 AM
    Maybe dumb, but is there a way to write a when state for strings, but for one of the string cases I want there to be a wild card at the end? My scenario is when matching routes but some routes have arguments at the end.
    when (request.path) {
        "/api/one/two" ->
            return "blah"
        "/api/three/four?arg=myArg" ->
            return "boop"
    I want the second case to basically be
    api/three/four*
    instead of hard coding the arg. Or do I have to basically refactor this and just use endsWith or something?
    d
    • 2
    • 5
  • p

    poohbar

    07/09/2021, 9:20 PM
    how could I make this a singleton? it seems like
    object
    can’t do generics?
    class Mapper<T : Account> : RecordMapper<Record, T> {
        override fun map(record: Record?): T? {
            TODO("Not yet implemented")
        }
    }
    Even better, I really just need a function, where the input is
    Record
    and the output is
    T: Account
    how do I declare that?
    d
    d
    +2
    • 5
    • 20
  • o

    oday

    07/10/2021, 9:41 PM
    I’d like to walk in 2 loops over 0 to half of string and then end of string back to half, this doesn’t look like the way to do it
    for (i in 0 until halfIndex) {
                    for (j in s.length downTo halfIndex) {
                        println("i: ${s[i]} j: ${s[j]}")
                    }
                }
    s
    e
    k
    • 4
    • 23
  • a

    Ayfri

    07/12/2021, 5:44 AM
    Hi, how can I set a function abstract for a companion object of a class ?
    s
    e
    +2
    • 5
    • 6
  • o

    oday

    07/12/2021, 12:29 PM
    I’m following this code along with the debugger, and I’m very confused as to when or why
    head
    ends up changing and pointing to new elements https://paste.ofcode.org/3h6juagTuPwvZaDEeTkwCP
    s
    • 2
    • 16
  • o

    oday

    07/14/2021, 9:30 AM
    is this python code not equivalent to this Kotlin code?
    val leftOne = arrayOne.drop(0).filter { it < arrayOne.first() }.toIntArray()
    u
    t
    d
    • 4
    • 9
  • o

    oday

    07/16/2021, 6:16 PM
    how exactly do I use
    assert()
    ?
    assert(1 == 1, { "Equal" })
    shows nothing in the console
    y
    z
    e
    • 4
    • 10
  • d

    DMITRY.

    07/17/2021, 2:28 PM
    Hello! Is it possible to write tests in the same file as a function? I want to organize my solutions for the tasks I solve on Codewars Something like this:
    s
    c
    e
    • 4
    • 4
  • p

    Pāvels Garklāvs

    07/18/2021, 6:12 PM
    Hello, I am starting a project with KotlinJS/React and wondering if its possible to use tailwindCSS with it. If yes then how do I achieve that?
    t
    • 2
    • 1
  • m

    Miguel

    07/19/2021, 9:15 AM
    Hey everyone! I've been using Kotlin for a year now, mostly in the backend and some Android. I've recently created a WebApp with Kotlin + Ktor framework, and discovered a different way of loading/presenting HTML, using FreeMarker. I've created my WebApp following a guide, this one! I am now trying to explain what was done to some of my peers and I encountered a problem.. Imagine you have the following routes available in your API (server): • /home • /projects When the browser hits those routes, the server application has some logic that needs to be executed, after processing what it needs, the server answer the browser with an HTML template through the use of FreeMarker. My question to you is where is the client in all of this? In a "normal" full stack web app I was expecting to see a clear separation between Client and Server. Something of the sorts of: 1. Browser makes a request. 2. Client receives it, does some validation 3. Sends the request to the server 4. Server processes/retrieves data 5. Server answers the client (a JSON for example) 6. Client receives the JSON and builds/fills an HTML page with the data. 7. The browser loads the different HTML. !! This is an oversimplification of things, but I think it can convey the idea of what I was expecting versus the reality !! This is the reality: 1. Browser makes a request. 2. Server app receives and processes it 3. Answers the browser with an HTML page, via FreeMarker. Code snippet retrieved from the guide I linked above:
    fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
    
    fun Application.module() {
        install(FreeMarker) {
            templateLoader = ClassTemplateLoader(this::class.java.classLoader, "templates")
            outputFormat = HTMLOutputFormat.INSTANCE
        }
        routing {
            static("/static") {
                resources("files")
            }
            get("/") {
                call.respond(FreeMarkerContent("index.ftl", mapOf("entries" to blogEntries), ""))
            }
    Is it safe to say there's no client? Is that even a thing? Sorry for the long format, I'm a bit confused, if after reading this you are too, I can clarify it further.
    h
    t
    c
    • 4
    • 10
  • m

    MisileLab

    07/20/2021, 2:51 AM
    hi, i'm new in kotlin.
    Could not find method implementation() for arguments [org.jetbrains.kotlin:kotlin-test-junit:1.5.21] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
    What is this error mean and how to fix it? My build.gradle
    /*
     * This file was generated by the Gradle 'init' task.
     */
    
    repositories {
        mavenCentral()
        maven {
            url = uri("<https://papermc.io/repo/repository/maven-public/>")
        }
    
        maven {
            url = uri("<https://oss.sonatype.org/content/groups/public/>")
        }
    
        maven {
            url = uri("<https://repo.maven.apache.org/maven2/>")
        }
    }
    
    dependencies {
        implementation("org.jetbrains.kotlin:kotlin-test-junit:1.5.21")
        implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.5.21")
        implementation("io.github.monun:kommand-api:2.2.0")
        compileOnly("io.papermc.paper:paper-api:1.17.1-R0.1-SNAPSHOT")
    }
    
    java.sourceCompatibility = JavaVersion.VERSION_1_8
    
    publishing {
        publications.create<MavenPublication>("maven") {
            from(components["java"])
        }
    }
    
    tasks.withType<JavaCompile> {
        options.encoding = "UTF-8"
    }
    a
    v
    • 3
    • 3
  • a

    Ayfri

    07/20/2021, 8:36 AM
    Hi, is there an equivalent of
    console.count("something")
    in Kotlin JVM ? Documentation of console.count : https://developer.mozilla.org/en-US/docs/Web/API/Console/count
    h
    e
    • 3
    • 2
  • s

    skwalking

    07/21/2021, 9:21 AM
    Hi I was trying to understand the flow in below code:
    1 class Person(val pets: MutableList<Pet> = mutableListOf())
    2
    3 class Pet {
    4     constructor(owner: Person) {
    5         owner.pets.add(this) // adds this pet to the list of its owner's pets
    6     }
    7 }
    Can someone please use above code to make an example on printing something. Since I'm unable to understand the flow of the code I'm also unable to find what "this" in code line no. 5 does. Thank you 🙂
    c
    h
    • 3
    • 2
  • s

    Sudhir Singh Khanger

    07/21/2021, 11:17 AM
    var drivingStyle = when (getWeatherConditions()) {
       "Sunny" -> "Speedy"
       "Foggy", "Rainy" -> "Safely"
       "Blizzard" -> "Don't drive!"
       else -> "Undefined"
    }
    And
    sealed class Weather
    object Rainy : Weather()
    object Sunny : Weather()
    object Foggy : Weather()
    object Blizzard : Weather()
    
    var drivingStyle = when (getWeatherConditions()) {
       Sunny -> "Speedy"
       Foggy, Rainy  -> "Safely"
    }
    1. What is the benefit of using Sealed classes in this case over
    const
    ? Is it expensive to create a Sealed class over a constant? The one benefit I see is that I don't have to add
    else
    branch if I use all classes of the Sealed class. 2. When a derived class of a Sealed class is used in a when block then does when know all the classes which extend a sealed class?
    m
    a
    • 3
    • 4
  • t

    Tristan

    07/21/2021, 9:29 PM
    Hello, Is there the possibility in Kotlin to retrieve statically the return type or parameters of a function? In TypeScript it is possible to things like, I don't know about Kotlin.
    fun getSomething(): Something {}
    
    val something: ReturnType<typeof getSomething> = getSomething()
    It may be useful for situation where:
    fun executeSomething(cb: Something.(arg: String) -> Unit) {
        val something = Something()
        something.cb("the arg")
    }
    
    // here the type could be different
    // val cb: Parameters<executeSomething>[0] = {
    val cb: SecretUser.(arg: String) -> Unit = {
        println(propertyOfSomething)
    }
    
    executeSomething(cb)
    I am just playing with the language 😊
    l
    • 2
    • 2
  • m

    MisileLab

    07/22/2021, 3:14 AM
    how to make async tesk in kotlin?
    h
    w
    • 3
    • 3
  • o

    oday

    07/23/2021, 9:33 AM
    is this
    for (i in 1 until array.size)
    the best equivalent to this?
    for num in array[1:]
    r
    k
    p
    • 4
    • 12
  • o

    oday

    07/23/2021, 5:51 PM
    where can I store elements of different types? both Int and IntArray for example
    m
    • 2
    • 4
  • k

    kv

    07/23/2021, 6:28 PM
    I have a
    mutableListOf<Pair?>
    that I want to check the contents of. I try something like this on Kotlin 1.5.21:
    fun foo(value: List<Pair?>): Boolean {
            return list.contains(value)
        }
    I get the following error:
    Type inference failed. The value of the type parameter T should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly.
    I can remove the error by modifying it to
    return list.contains<Any?>(value)
    but it feels like a weird work around. Anyone got insight as to the best way to approach this?
    e
    c
    • 3
    • 4
  • m

    MisileLab

    07/24/2021, 3:09 AM
    I have this error in IDE.
    Use of enum entry names as types is not allowed, use enum type instead
    My Code https://pastebin.com/jfgSNRJu
    e
    • 2
    • 3
  • k

    keishi kubo

    07/24/2021, 12:23 PM
    I want to access parent class constructor from extended class. Like this.. How can I do this ?
    class A {
      generateInstance(): this:class {
         return this::class()
      }
    }
    class B: A() 
    val b: B = B().generateInstance()
    e
    a
    t
    • 4
    • 5
  • a

    Ayfri

    07/28/2021, 3:08 PM
    Hi, I know that there are names for specific functions, like a function with an argument that returns a Boolean is a Predicate, but is there a name for a function that has an argument of type T and returns the same type ? Like this
    typealias IDK<T> = (value: T) -> T
    r
    v
    +3
    • 6
    • 8
  • s

    smit01

    07/29/2021, 6:00 PM
    I still get confused with kotlin generics and delegated properties any good references. I have tried to understand it through official doc but it didn't really helped me so of someone can provide good reference or explain it. <*> projection confuses me
    👍 1
    a
    m
    +2
    • 5
    • 7
Powered by Linen
Title
s

smit01

07/29/2021, 6:00 PM
I still get confused with kotlin generics and delegated properties any good references. I have tried to understand it through official doc but it didn't really helped me so of someone can provide good reference or explain it. <*> projection confuses me
👍 1
a

Alejandro Rios

07/29/2021, 6:12 PM
https://typealias.com/guides/ins-and-outs-of-generic-variance/
:kotlin-intensifies: 1
https://typealias.com/guides/star-projections-and-how-they-work/
:kotlin-intensifies: 1
m

mkrussel

07/29/2021, 8:39 PM
Those are the best guides I've seen on variance, and would recommend everyone read them.
👍 1
m

Michael Schleichardt

07/29/2021, 9:12 PM
Assume you have a Type
Thing<T>
The <*> projection means you neither want to read nor write something with
T
, but you still can use non-generic methods like
size
on
List
which returns just a number.
👍 1
c

CLOVIS

07/30/2021, 7:17 PM
How similar is
*
and
Nothing
? In both cases, a function that returns it can't be called
m

mkrussel

07/30/2021, 7:21 PM
If I remember correctly using
*
makes all in usages of the type be
Nothing
and all outs act as
Any?
(or the upper bounds if not the default.
a

Alejandro Rios

07/30/2021, 7:42 PM
@CLOVIS
Star projections
link explain about it
View count: 2