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

    Smallville7123

    04/09/2019, 7:00 AM
    there are probably more primitive types that i am missing
    d
    k
    • 3
    • 14
  • s

    Slackbot

    04/10/2019, 7:46 AM
    This message was deleted.
    k
    • 2
    • 1
  • s

    Smallville7123

    04/10/2019, 9:47 AM
    ok i think i can successfully create instances of inner classes now, however this does not work if security manager is active
    class A {
        inner class B {
            inner class C {
                var empty: Int = 0
            }
    
            var empty: Int = 0
            var a: MutableList<C>
    
            init {
                a = mutableListOf(C())
            }
        }
    
        var a: MutableList<B>
    
        init {
            a = mutableListOf(B())
        }
    
        /**
         * test variable
         */
        var empty: Int = 0
    }
    
    fun getDeclaringUpperLevelClassObject(objectA: Any?): Any? {
        if (objectA == null) {
            return null
        }
        val cls = objectA.javaClass ?: return objectA
        val outerCls = cls.enclosingClass
            ?: // this is top-level class
            return objectA
        // get outer class object
        var outerObj: Any? = null
        try {
            val fields = cls.declaredFields
            for (field in fields) {
                if (field != null && field.type === outerCls
                    && field.name != null && field.name.startsWith("this$")
                ) {
                    /*
                    `field.isAccessible = true` does not work with a Security Manager
                    java.security.AccessControlException: access denied
                    ("java.lang.reflect.ReflectPermission" "suppressAccessChecks")
                    */
                    field.isAccessible = true
                    outerObj = field.get(objectA)
                    break
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    
        return outerObj
    }
    
    /**
     * returns a [MutableList] of classes parenting the current class
     *
     * the top most class is always the last index
     *
     * the last class is always the first index
     *
     * for example: up(f[0].a[0].a[0]) = 0(f[0].a[0].a[0]) 1(f[0].a[0]) 2(f[0])
     */
    fun up(a: Any, m: MutableList<Any> = mutableListOf(), debug: Boolean = false): MutableList<Any> {
        m.add(a)
        if (debug) println("get upper class of ${a.javaClass.name}")
        val upperC = getDeclaringUpperLevelClassObject(a)
        if (upperC == null) abort("upperC is null o.o")
        if (a.equals(upperC)) return m
        else {
            return up(upperC, m)
        }
    }
    
    /**
     * use as follows: `instanceChain(`[up]`(f[0]))`
     */
    fun instanceChain(chain: MutableList<Any>, index: Int = chain.lastIndex, debug: Boolean = false): Any {
        return if (index == 0) {
            chain[index]
        } else {
            if (debug) println("chain[$index] = " + chain[index])
            val outer = chain[index]
            val toRun = Class.forName(chain[index].javaClass.name + "$" + chain[index - 1].javaClass.simpleName)
            val ctor = toRun.getDeclaredConstructor(chain[index]::class.java)
            val lowerCInstance = ctor.newInstance(outer)
            if (debug) println("lowerCInstance = " + lowerCInstance!!::class.java)
            if (index == 1) lowerCInstance
            else instanceChain(chain, index - 1)
        }
    }
    
    fun Test() {
        val f = mutableListOf<A>()
        f.add(A()) // this is required, i do not know how to do accomplish this in the init block
        println("f[0] = ${instanceChain(up(f[0]))}")
        println("f[0].a[0] = ${instanceChain(up(f[0].a[0]))}")
        println("f[0].a[0].a[0] = ${instanceChain(up(f[0].a[0].a[0]))}")
        abort()
    }
    🤢 2
    s
    • 2
    • 17
  • p

    Paul N

    04/11/2019, 6:47 PM
    Say I've got a World class. A world can contain Spheres, and a Sphere can have properties such as Colour. So on my World class I have a factory function within a companion object called defaultWorld. This returns me an instance of a World with two Colour.RED Spheres. What's the best way of taking a defaultWorld and modifying it so that, for example, one of the Sphere's is Colour.BLUE not RED ? At the moment all the attributes of Sphere are val's not vars, so I can't just do world.spheres[0].colour=Colour.BLUE. And even if I did change it to var, that changes the defaultWorld for everything. So what's the best way of having some sort of template object that I can easily create new variants from ?
    🤔 1
    s
    k
    +3
    • 6
    • 6
  • h

    Hullaballoonatic

    04/11/2019, 8:28 PM
    Unrelated question. How is
    MutableList
    both an interface and a class in the stdlib without their names clashing? Do they have separate jvmNames?
    s
    d
    +2
    • 5
    • 17
  • j

    Joe

    04/12/2019, 6:13 PM
    if I have a
    Map<String, Thing?>
    is there an equivalent of
    Iterable#filterNoNull()
    that will give me a
    Map<String,Thing>
    for all non-null values?
    s
    s
    a
    • 4
    • 14
  • o

    oday

    04/13/2019, 12:53 PM
    like say I have this
    var mileageValuesToYears = mapOf(
        1980 to 900000,
        1981 to 900000,
        1982 to 100000,
        1983 to 120000
    )
    k
    a
    +2
    • 5
    • 5
  • a

    Akram

    04/13/2019, 1:37 PM
    Hello guys , does anyone have nice tutorials or articles to start with annotation processing
    b
    t
    • 3
    • 8
  • s

    Slackbot

    04/15/2019, 4:15 AM
    This message was deleted.
    t
    • 2
    • 1
  • s

    Srikumar

    04/15/2019, 3:29 PM
    I just joined this group and I have a question about Testing frameworks in Kotlin. I find Spock's data driven testing very useful and was wondering if there was anything similar to that in Kotlin frameworks? I have checked out Spek, but found its data driven testing (parameterised) to be too restrictive and verbose
    t
    m
    • 3
    • 10
  • o

    oday

    04/15/2019, 3:29 PM
    is it “hacky” to use ::isInitialized?
    w
    k
    k
    • 4
    • 5
  • c

    colljos

    04/16/2019, 12:58 PM
    Hi, I’m porting a fairly large Kotlin codebase to run under Java 9/10/11 (in a first instance just being compatible with Java 9 modules using classpath/UNNAMED-MODULE), but am hitting some fairly basic obstacles with the Kotlin compiler. Please reply if you have any experience in this area.
    i
    s
    • 3
    • 8
  • o

    oday

    04/17/2019, 8:07 AM
    what’s the default/suggested/safest/recommended way to initialize stuff like this ? http://snpy.in/kISHVt
    i
    d
    n
    • 4
    • 16
  • m

    matt tighe

    04/17/2019, 7:05 PM
    is it at all possible to type anonymous objects dynamically? i’m trying to do something like this:
    fun reportError(errorState: ErrorState) {
        val type = object : Exception {
             type.className = errorState.className
        }
        silentlyReportException(type)
        handleDifferentErrorStates(errorState)
    }
    p
    r
    • 3
    • 4
  • c

    cspotcode

    04/17/2019, 9:10 PM
    Can I reuse the constructor signature of a superclass, so that I don't have to re-type all the arguments of the constructor?
    open class SuperClass(val foo: String, val bar: String) {}
    open class SubClass : SuperClass {}
    val instance = SubClass(foo = "hello", bar = "world") // <-- subclass has same constructor signature as superclass without needing to re-type the signature in SubClass's declaration
    k
    • 2
    • 2
  • s

    Slackbot

    04/18/2019, 6:05 AM
    This message was deleted.
    t
    m
    • 3
    • 3
  • s

    Smallville7123

    04/18/2019, 6:25 AM
    how do i pass a vararg to a vararg
    m
    • 2
    • 2
  • s

    Smallville7123

    04/18/2019, 6:26 AM
    eg,
    fun String?.tokenizeVararg(vararg delimiters: String, returnDelimiters: Boolean = false): List<String>? {
        return if (this == null) null
        else this.tokenizeVararg(delimiters = delimiters, returnDelimiters = returnDelimiters)
    }
    Assigning single elements to varargs in named form is forbidden
    Type mismatch: inferred type is Array<out String> but String was expected
    s
    • 2
    • 1
  • s

    Smallville7123

    04/18/2019, 12:18 PM
    how do i compare
    Number
    for example
    fun Number.comparisionsGreaterThan(i: Number): Boolean {
        return this < i
    }
    w
    s
    +2
    • 5
    • 58
  • s

    Slackbot

    04/19/2019, 1:32 AM
    This message was deleted.
    s
    • 2
    • 3
  • a

    Ary Sugiarto

    04/19/2019, 9:19 AM
    Ask, Suggest where fundamental learning kotlin?
    k
    s
    +2
    • 5
    • 7
  • o

    oday

    04/19/2019, 4:36 PM
    hey guys, i have list A and list B, I want to go over B and set some property inside A depending on what I find in B, I wanna do this without 2 literal loops
    s
    i
    • 3
    • 18
  • s

    sophiataskova

    04/20/2019, 3:04 AM
    Or rather, what would be an idiomatic way to describe some expectations that need to be fulfilled in the test, within a certain timeout?
    d
    • 2
    • 1
  • o

    Oleh Ponomarenko

    04/22/2019, 2:04 PM
    Can I always use Kotlin's Object instead of usual structure of getting Singleton in Java? http://prntscr.com/nfb8xr Or it can bring some problem? for example in time working in different threads.
    d
    n
    d
    • 4
    • 5
  • n

    Novoa

    04/23/2019, 11:15 PM
    Would somebody please help me understand what is happening with a function declaration like the following?
    fun foo(): String = "bar"
    What I understand is that function foo takes no parameters and has a return type of String. What is odd to me coming from other languages where I have never seen this, is that it is valid for there to be no body declaration but just an equal sign after the return type assigning the return value as a constant. If you could, would you please provide a use case for a function declared similarly?
    s
    c
    • 3
    • 8
  • n

    Nezteb

    04/24/2019, 4:55 PM
    Does
    mapOf
    have any form that tapes type parameters? Like
    mapOf<String, Int>(...)
    ?
    s
    s
    a
    • 4
    • 5
  • d

    df

    04/25/2019, 9:39 AM
    is there a more idiomatic way in kotlin to write sth. like this?
    while (true) {
        val rows = repo.findAll(page)
    
        if (rows.isEmpty()) {
            break
        }
    
        doSomething(rows)
    }
    p
    d
    d
    • 4
    • 10
  • t

    Tim Fennis

    04/25/2019, 1:09 PM
    I have an enum which is defined in Java and has the property name, which is a string. now when I try to fetch this I get an Overload resolution ambiguity error, because Kotlin itself -also- defines name as a String, how do I access .name from the original enum class now? (Without using reflections)
    p
    i
    • 3
    • 20
  • b

    bjonnh

    04/26/2019, 8:16 PM
    what's the difference between the data class code and the java code presented?
    s
    • 2
    • 1
  • b

    bjonnh

    04/26/2019, 8:52 PM
    This works:
    @SolrDocument(solrCoreName ="indexedcitation")
    class IndexedCitation {
        @Id
        @Indexed(name = "id", type = "string")
        private var id: String? = null
    
        @Indexed(name = "title", type = "string")
        private var title: String? = null
    
    
        fun getId(): String? {
            return id
        }
    
        fun setId(id: String?) {
            this.id = id
        }
    
        fun getTitle(): String? {
            return title
        }
    
        fun setTitle(title: String?) {
            this.title = title
        }
    }
    but not:
    @SolrDocument(solrCoreName ="indexedcitation")
    data class IndexedCitation(
        @Id
        @Indexed(name = "id", type = "string")
        private var id: String? = null,
    
        @Indexed(name = "title", type = "string")
        private var title: String? = null
    
    )
    p
    r
    • 3
    • 23
Powered by Linen
Title
b

bjonnh

04/26/2019, 8:52 PM
This works:
@SolrDocument(solrCoreName ="indexedcitation")
class IndexedCitation {
    @Id
    @Indexed(name = "id", type = "string")
    private var id: String? = null

    @Indexed(name = "title", type = "string")
    private var title: String? = null


    fun getId(): String? {
        return id
    }

    fun setId(id: String?) {
        this.id = id
    }

    fun getTitle(): String? {
        return title
    }

    fun setTitle(title: String?) {
        this.title = title
    }
}
but not:
@SolrDocument(solrCoreName ="indexedcitation")
data class IndexedCitation(
    @Id
    @Indexed(name = "id", type = "string")
    private var id: String? = null,

    @Indexed(name = "title", type = "string")
    private var title: String? = null

)
p

Pavlo Liapota

04/26/2019, 9:00 PM
You can specify for which element annotation should be used: https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets
b

bjonnh

04/26/2019, 9:03 PM
so correct me if I'm wrong but in that case it would be @field:String ?
p

Pavlo Liapota

04/26/2019, 9:28 PM
@field:Id
I don’t know which target you need (field, set or get), you can try several.
b

bjonnh

04/26/2019, 9:52 PM
I can't set these on the @Indexed parameters
and trying all combinations on @Id do not change anything (the only one that work on @Indexed is field.
https://gist.github.com/bjonnh/5493eb89fbc0207679d75cab8b3938b1
bytecode of the dataclass
https://gist.github.com/bjonnh/bc91bedd8b23dccbfd947d9a8d707b42
bytecode of the public class
(no idea if it is useful or not)
ok it seems that the problem arises when I have a constructor
r

Robert Jaros

04/27/2019, 8:22 PM
Do you use allopen plugin? the classes are final in the bytecode you posted and spring doesn't like final classes - it can give weird errors.
b

bjonnh

04/27/2019, 8:35 PM
what is that plugin?
(reading https://www.baeldung.com/kotlin-allopen-spring)
Is there any expected negative side effect of using that plugin?
r

Robert Jaros

04/27/2019, 9:00 PM
not really
👌 1
all your classes will be open by default just like in Java
there is also kotlin-spring plugin, which works the same way but only for classes annotated with Spring annotations
https://kotlinlang.org/docs/reference/compiler-plugins.html#spring-support
definitely worth applying before testing spring with kotlin
b

bjonnh

04/27/2019, 9:06 PM
first time I get stung by that but yep I'll clearly try that
But I cannot make data classes open
seems to work anyway. Thanks
View count: 3