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

    Michał Kalinowski

    10/17/2019, 3:36 PM
    let's say I want map enum to and from my own strings, so I just
    override fun toString()
    , and now I would like make
    constructor(type: String)
    that will create enum from appropriate string, anyone have idea how to accomplish such thing?
    r
    • 2
    • 4
  • u

    ursus

    10/19/2019, 2:56 AM
    A: fun foo(parentId: Long, itemId: Long) 
    B: fun foo(itemId: Long, parentId: Long)
    m
    d
    • 3
    • 4
  • t

    Tuang

    10/19/2019, 1:15 PM
    First of all my question may not be relate to Kotlin,, Why
    QueryRunner().query()
    return
    Long
    , is it depending on what Handler is using? For example my code is like this
    val query = "SELECT COUNT(*) FROM goods_user_rel WHERE _goods_id = ?"
    val count = QueryRunner().query(connection, query, ScalarHandler<Long>(), goodsId)
    The first time i wrote
    ScalarHandler<Int>()
    and i got error something likes
    java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
    Then i change
    ScalarHandler<Int>()
    to
    ScalarHandler<Long>()
    and it’s work but i have no idea why
    Long
    is return
    d
    • 2
    • 1
  • t

    Tuang

    10/20/2019, 12:05 AM
    Good morning from japan. So now i am stucking in companion object.
    class Myclass(val name: String, val age: Int) {
        private someProperty = .....
        private someProperty = .....
        companion object {
            @JvmStatic
            val instance = Myclass(name = ??  , age = ??)
        }
    }
    how to set name and age value inside the companion object?
    a
    • 2
    • 5
  • f

    Florian

    10/20/2019, 5:05 PM
    I see a lot of discussion about Kotlin and functional programming. I have a very basic beginner question: Just doing stuff in file-level functions doesn't mean I am doing "functional programming", right?
    😆 1
    a
    a
    +2
    • 5
    • 14
  • t

    toffe

    10/21/2019, 10:44 AM
    Hi guys. I'm new on this Kotlin train. Have been coding with kotlin for 1.5 years but never started my own project. I currently have a NodeJS application running on a raspberry pi controlling a underwater vehicle (ROV). I thought Kotlin would maybe be a upgrade for this project. But not sure how to start it. The NodeJS application hosts a web gui which streams video & controls.
    g
    a
    • 3
    • 3
  • a

    Arnau Díaz

    10/22/2019, 8:13 AM
    Hi guys, I'm having trouble understanding the difference between these: With abstract class:
    abstract class ParentObject(val id: Int)
    class ChildObject(id: Int, val value: String) : ParentObject(id)
    With adt/sealed class it doesn't compile:
    sealed class ParentObject(val id: Int)
    data class ChildObject(id: Int, val value: String) : ParentObject(id)
    Is there any way to get it working in Kotlin? I want the benefits of the data classes but there are some fields that are common for all my subtypes.
    s
    • 2
    • 2
  • e

    eekboom

    10/22/2019, 10:04 AM
    Consider this: Interface with a property. Class implements the interface using primary constructor with a parameter that overrides the property. Nice and easy. Now: How can I transform the argument value before that? There sure must be a better way than this:
    interface Foo { val text: String }
    
    class Bar (private var text2: String) : Foo {
        init {
            text2 = text2.replace('a', 'z')
        }
        override val text: String
            get() = text2
    }
    k
    • 2
    • 2
  • l

    LastExceed

    10/22/2019, 10:11 AM
    how do i set up modules in IntelliJ ? I rightclicked the mainproject and added a module from there but the module has no source folder by default and when I create it manually it doesnt give me the presets for creating kotlin files ect (and when i create those manually as well i dont have any syntax highlighting, code completion ect)
    e
    • 2
    • 18
  • s

    scottiedog45

    10/22/2019, 5:03 PM
    Is there a way to initialize an object from a primitive type? Something like
    data class Foo(val a: String) {
        
        init {
            //magic that takes string and sets it to a
        }
    }
    
    var Bar : Foo = "b"
    s
    • 2
    • 8
  • p

    Peter

    10/22/2019, 6:01 PM
    Hello everyone, A bit about me then the question: I use Kotlin almost 5 months now. I have been programming for about 2 years total(1.5 year trying to learn Java - spring, 5 months professionally). Currently I am using Kotlin with Spring Batch & Boot. All this time I have been skipping Concurrency "for later" and I think the time has come now. I am thinking If you guys as most experienced individuals, would suggest I skip Java concurrency and dive directly to Kotlin concurrency/coroutines? Will I miss "important background" if I do that, or is it completely normal to start my journy with kotlin? Thanks.
    e
    • 2
    • 2
  • s

    Sandeep Kumar

    10/22/2019, 11:18 PM
    I’m hoping to get some pointers that will help me work around this issue. I’m having trouble getting the following simple-minded controller to work correctly with Spring Framework 5.2, Springboot 2.2 and Kotlin 1.3.50. It’s a simple FileServerController that serves files below ~ but I seem to get double invocations of the controller and the mime-type of the returned file is always application/json even when I set it explicitly (as below). If I don’t return xml files with the correct mime-type, then I can’t get the browser to perform XSL transformations on it. I have a feeling (but not positive) that the non-Kotlin version of it would work. But I want to get started on Kotlin.
    @Controller
    class FileServerController {
        @RequestMapping(value = ["/**"])
        fun getFile(request: HttpServletRequest, response: HttpServletResponse): FileSystemResource {
            var fileName = request.servletPath
            val HOME = System.getenv("HOME")
    
            println("Requested ${fileName}")
    
            fileName = "${HOME}${fileName}"
            val file = File(fileName)
    
            if (file.canRead()) {
                println("Serving ${fileName}")
                if(fileName.endsWith(".xml")) {
                    response.contentType = "text/xml"
                } else if(fileName.endsWith(".xslt")) {
                    response.contentType = "application/xslt+xml"
                }
                return FileSystemResource(file)
            } else {
                println("Couldn't find ${fileName}")
                throw NotFoundException(fileName)
            }
        }
    }
    The dependencies in my pom.xml are
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-reflect</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jdk8</artifactId>
        </dependency>
    k
    c
    b
    • 4
    • 11
  • p

    Pranjal Desai

    10/23/2019, 7:05 PM
    Hi, I’m currently using picasso and I was wondering if there was a solution to if I want to download a image from the url, and the next time the url is passed it uses the local downloaded version
    r
    k
    • 3
    • 4
  • f

    Florian

    10/26/2019, 1:35 PM
    there is no way to access a field of a class directly from the outside ever?
    k
    s
    • 3
    • 11
  • f

    Florian

    10/28/2019, 8:55 AM
    These two are equivalent, correct? (I know they could be inlined in the constructor) Edit: Forgot to remove the first two assignments in the 2nd snippet, just think that away
    :yes: 1
    s
    e
    j
    • 4
    • 5
  • m

    Matheus

    10/28/2019, 8:31 PM
    I am having trouble implementing a method from an interface that was defined in Java. It has a
    Class<T>
    return type, but I can't seem to make it work with nullable types without triggering a compiler warning
    override fun toType(): Class<Boolean?> = 
            Boolean::class.java as Class<Boolean?>
    This works, but the cast triggers the warning:
    Unchecked cast Class<Boolean> to Class<Boolean?>
    I tried to qualify it as <out Boolean>, but I can't seem to make it work?
    z
    r
    d
    • 4
    • 21
  • f

    Florian

    10/29/2019, 10:16 AM
    On the JVM,
    Int?
    uses Java's
    Integer
    class?
    d
    • 2
    • 9
  • v

    vlad.minaev

    10/30/2019, 10:23 PM
    dumb question about generics - what is wrong?
    fun <T : User>gen(): List<T> = listOf(User())
    r
    k
    m
    • 4
    • 14
  • a

    antoniomarin

    11/01/2019, 10:08 AM
    Quick question, I’m looking for cleanest approach to create recyclerView list with headers based on the particular object value, in this case
    userLocation
    . This code wont work, because
    it.userlocation.forEach
    will loop through string characters but you get an idea what I’m trying to do
    • 1
    • 1
  • l

    leosan

    11/01/2019, 4:46 PM
    is there any functional operator that helps me achieve this?
    val listOfLists = listOf(
         Data(1, listOf("A")),
         Data(2, listOf("B")),
         Data(1, listOf("B")),
         Data(2, listOf("C"))
      )
       output:  [ Data(1,listOf("A","B")) , Data(2,listOf("B","C"))]
    c
    l
    • 3
    • 7
  • m

    morozov

    11/02/2019, 7:13 PM
    tried smth like this
    target?.let { targetList.sortedWith(compareBy {it.priority == 1})}
    m
    • 2
    • 16
  • h

    Harsh Rathod

    11/05/2019, 9:28 AM
    Is there any free ebook to learn Kotlin?
    t
    r
    m
    • 4
    • 3
  • f

    Frodrigues

    11/05/2019, 3:33 PM
    private fun fullFunc(func: () -> Unit): () -> Unit = { beforeFunc; func; afterFunc }
    m
    d
    • 3
    • 3
  • g

    Goose

    11/05/2019, 3:43 PM
    Howdy from Denver! I’m a Full-Stack Java dev looking to make the transition to Kotlin/Android. Excited to join this community!
    👍 3
    👋🏼 3
    m
    • 2
    • 4
  • f

    Frodrigues

    11/05/2019, 9:42 PM
    And the child instantiates that two objects in the constructor?
    s
    • 2
    • 2
  • c

    Colton Idle

    11/06/2019, 4:15 AM
    Hey everyone! In Android land I write a lot of interfaces in kotlin that have one method. A SAM is what I think they call em. Something like this
    interface SaveListener {
        fun onSave(name: String)
     }
    MY ISSUE: When I try to create the listener, it makes me write out the whole thing. I thought there was a way around this in Kotlin? Probably missing something basic. So I have to write this
    myController.listener = object : SaveListener {
        override fun onSave(name: String) {
            //do thing
        }
    }
    But with kotlin I thought I'd be able to do this
    myController.listener = SaveListener { //do thing }
    m
    a
    +3
    • 6
    • 11
  • a

    andrzej

    11/06/2019, 9:00 AM
    but if I want to keep that interface (not a HOF), e.g. because of Spring (AFAIK you cannot inject implementation classes based on HOF), then what? Edit: this is an issue because when using Spring, I need interfaces (and cannot use HOF) and in tests I must use this verbose syntax for Kotlin interfaces (for legacy Java interfaces the short syntax - lambda works great)
    😭 1
    t
    • 2
    • 22
  • m

    Mani

    11/06/2019, 10:07 AM
    Folks, is there a better way to do this?
    val pickableState = try {
                PickableState.valueOf(state)
            } catch (ex: Exception){
                null
            }
    m
    • 2
    • 1
  • j

    Jesse Stolwijk

    11/06/2019, 10:21 AM
    PickableState.values().singleOrNull { it.name == state }
    👍 3
    m
    • 2
    • 2
  • s

    scottiedog45

    11/06/2019, 12:36 PM
    Is it weird to get a context reference from a view, for something slightly unrelated? For something like this, where
    z
    is a textView:
    z.text = z.context.getString(R.string.empty)
    t
    a
    • 3
    • 10
Powered by Linen
Title
s

scottiedog45

11/06/2019, 12:36 PM
Is it weird to get a context reference from a view, for something slightly unrelated? For something like this, where
z
is a textView:
z.text = z.context.getString(R.string.empty)
t

tseisel

11/06/2019, 1:11 PM
This is perfectly fine as long as you dont keep a reference to the
Context
that outlives the `Fragment`/`Activity` where the
View
is defined (this would result in memory leaks). Note that in your sample code, you could have used
z.setText(R.string.empty)
, which internally does what your code is doing : accessing resources from its Context.
a

Alex Crafford

11/06/2019, 1:23 PM
I'm struggling to think of a scenario where you would need to reference context this way. Like @tseisel said setText would get context on its own, but even that is un-necessary in Kotlin, it can and arguably should be set more explicitly using the '=' operator. For example:
z.text = resources.getString(R.string.empty)
or
z.text = ""
s

scottiedog45

11/06/2019, 1:29 PM
@Alex Crafford Here is the function for context. I was thinking I could eliminate the
context
parameter:
fun replaceEmptyDataWithLiteralEmptyStringIfNeeded(c: Context, textViews: List<TextView>, data: List<String?>) {

    (textViews zip data).forEach { z ->

        if (!z.second.isNullOrEmpty()) {
            z.first.text = z.second
            z.first.setTypeface(null, Typeface.NORMAL)
        } else {
            z.first.text = c.getString(R.string.empty)
            z.first.setTypeface(null, Typeface.ITALIC)
        }
    }
}
a

Alex Crafford

11/06/2019, 1:31 PM
I think I would eliminate the context param, and use a string literal there as long as it will always be an empty string.
s

scottiedog45

11/06/2019, 1:32 PM
It will not always be an empty string, sometimes I will have to
getString
. Ah- that empty string is literally the word “empty” 😅
a

Alex Crafford

11/06/2019, 1:33 PM
Oh ok, can that be set as the default text for the field?
s

scottiedog45

11/06/2019, 1:34 PM
It looks a little off in the UI as the the text is fetched over the network (the flash of “empty” has been deemed undesirable)
a

Alex Crafford

11/06/2019, 1:37 PM
Yeah that makes sense. Is this method inside of the parent fragment/activity or is it outside of that context entirely?
If this is in a ViewModel and not a Activity/Fragment, its probably best to not use context at all but rather change that param from Context to String which is passed from the view using. This way you don't risk memory leaks
s

scottiedog45

11/06/2019, 2:01 PM
Ah yes makes sense - thanks 😃
View count: 3