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
announcements
  • u

    ubu

    08/23/2018, 12:11 PM
    Hi guys. I'm trying to write a DSL. Suppose I have this structure:
    class A(val someObject : SomeObjectClass) {
    
        fun doSomethingWithSomeObject() {
            // TODO do something with someObject
        }
    }
    How would I achieve something like the following in Kotlin:
    coolDSL(someObject) {
    
        doSomethingWithSomeObject {
            someObject.callSomeMethod()
        }
    
    }
    Thanks in advance.
    d
    g
    • 3
    • 7
  • t

    temp_man

    08/23/2018, 4:03 PM
    Hello, I am trying to convert this line of Objective-C code to Kotlin´[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];´
    s
    g
    +2
    • 5
    • 6
  • t

    tschuchort

    08/23/2018, 8:46 PM
    Are questions regarding design patterns welcome? I have a tree of objects that I need to convert to a similar tree of other objects and the creation logic is quite complex. The object types are also in a hierarchy where only the leafs are non-abstract and can be instantiated. So right now I have a static factory method in each class that checks the necessary conditions and then returns the object or null (in the case of leaf types) or delegates the object creation to the right factory method of it's sub types (in the case of a non-leaf type). But I was thinking that it might be better to put all of that creation logic in a factory class. In particular, I think it will improve error handling since the nested nullable factory methods tend to swallow error reasons which makes debugging much harder. And since everything is in one place, there is less repetition of the necessary conditions for creating some object. But a big concern is that putting all the checks in the factory class would make it possible to create some class in an invalid state. I could of course also put the same checks into each constructor, but that repetition would make the whole thing pointless. What do you think? What are the pros/cons of one factory class vs nested factory methods vs checks in constructors that throw, and trying them all in order?
    r
    k
    l
    • 4
    • 3
  • b

    bdawg.io

    08/23/2018, 8:55 PM
    I did a compile to bytecode and decompile to java, and this appears to be the case:
    public static final void main(@NotNull String[] args) {
      Intrinsics.checkParameterIsNotNull(args, "args");
      MyType bar$iv = new MyType();
      doSomething(bar$iv);
    }
    🆒 1
    t
    • 2
    • 2
  • k

    karelpeeters

    08/23/2018, 11:19 PM
    boneless?
    s
    • 2
    • 7
  • j

    jurajsolarml

    08/24/2018, 11:15 AM
    Hello, you need to create activity in the menu / Mapa. Maps_activity is already created but located elsewhere. How can I do this? You can help me? I am a beginner. This is not working, it writes a mistake. Thank you Juraj override fun onOptionsItemSelected(item: MenuItem?): Boolean { when(item.itemId) { R.id.Mapa -> { startActivity(Intent(this, activity_maps::class.java)) return true } } return false } }
    m
    e
    • 3
    • 9
  • s

    sksk

    08/24/2018, 12:01 PM
    Hello, when will java 11/12 be supported ? i get this error message :

    https://i.imgur.com/icK7bBl.png▾

    • 1
    • 2
  • s

    supaham

    08/25/2018, 5:15 PM
    Hey, I'm working with android, when I try supply a 0xAARRGGBB number, with the alpha as FF, it requires me to cast to integer explicitly to apply it to an integer property, is there a way around that, or do I just keep casting to int?
    t
    k
    • 3
    • 8
  • c

    chickenfresh

    08/25/2018, 5:29 PM
    how can I use .find with data class inserted into sealed class?
    d
    • 2
    • 5
  • l

    lifter

    08/25/2018, 7:04 PM
    Can someone please explain why the second
    println(f())
    prints “Yes” instead of “No”?
    fun main(args: Array<String>) {
        var (f, x) = g()
        println(f()) // Prints "yes"
        x = 1
        println(f()) // Prints "yes"
    }
    
    fun g(): Pair<() -> Char, Int> {
        var x = 0
        var f = fun(): Char { return if (x == 0) { println("yes"); 'Y' } else { println("no"); 'N' } }
        return f to x
    }
    d
    k
    +2
    • 5
    • 21
  • c

    chickenfresh

    08/25/2018, 7:15 PM
    How to make working this
    val curSelectedItem = SimpleObjectProperty<ItemViewInstance>()
    with something like this
    when (curSelectedItem) { is ItemViewInstance.ItemModel }
    ? it works only if
    curSelectedItem
    isnt
    SimpleObjectProperty
    d
    s
    • 3
    • 16
  • f

    Felix

    08/26/2018, 8:49 PM
    Hi. Is there any public schedule for version 1.3 availability? I've some coroutines presentations scheduled for November and was wondering if should already use the "non-experimental" model of 1.3.
    o
    • 2
    • 2
  • j

    janvladimirmostert

    08/27/2018, 6:30 AM
    in the last few months upgrading Kotlin with every version, our build times became slower and slower builds used to take around 2 minutes max, now we're lucky if we get a
    mvn clean package
    to run in 20-24 minutes even with the incremental option on, that first
    mvn package
    or running it from IntelliJ takes almost 30 minutes not sure if Kotlin compile times became much slower or if our code-base became exponentially bigger we have about 2k lines of Java code and 114k lines of Kotlin code, so not that enormous any suggestions on how to make it faster?
    <plugin>
                    <artifactId>kotlin-maven-plugin</artifactId>
                    <groupId>org.jetbrains.kotlin</groupId>
                    <version>${kotlin.version}</version>
                    <configuration>
                        <jvmTarget>${java.version}</jvmTarget>
                        <compilerPlugins>
                            <plugin>jpa</plugin>
                        </compilerPlugins>
                        <pluginOptions>
                            <option>jpa:annotation=javax.persistence.MappedSuperclass</option>
                        </pluginOptions>
                    </configuration>
                    <executions>
                        <execution>
                            <id>compile</id>
                            <phase>generate-sources</phase>
                            <goals>
                                <goal>compile</goal>
                            </goals>
                            <configuration>
                                <sourceDirs>
                                    <source>src/main/java</source>
                                    <source>src/main/kotlin</source>
                                    <source>src/main/resources</source>
                                </sourceDirs>
                            </configuration>
                        </execution>
                        <execution>
                            <id>test-compile</id>
                            <phase>process-test-sources</phase>
                            <goals>
                                <goal>test-compile</goal>
                            </goals>
                            <configuration>
                                <sourceDirs>
                                    <source>src/test/java</source>
                                    <source>src/test/kotlin</source>
                                    <source>src/test/resources</source>
                                </sourceDirs>
                            </configuration>
                        </execution>
                    </executions>
                    <dependencies>
                        <dependency>
                            <groupId>org.jetbrains.kotlin</groupId>
                            <artifactId>kotlin-maven-noarg</artifactId>
                            <version>${kotlin.version}</version>
                        </dependency>
                    </dependencies>
                </plugin>
    d
    • 2
    • 4
  • j

    jacob

    08/27/2018, 8:01 AM
    is there any way to profile the build to see how much time each aspect is taking?
    j
    • 2
    • 1
  • c

    coder82

    08/27/2018, 9:37 AM
    why the HTML DSL doesn't have the crossorigin attribute? how to overcome this limitation?
    k
    • 2
    • 2
  • j

    Jakub

    08/27/2018, 1:35 PM
    Unfortunately, for tests I need to call private function
    fun read(bufferedReader: BufferedReader): List<String>
    because when mocking
    File
    ,
    file.bufferedReader
    gives
    NullPointerException
    k
    • 2
    • 2
  • j

    Jakub

    08/27/2018, 3:29 PM
    Thank you, what about Exceptions handling, IMO is better that I’m not handling IOException here, but pass it further to the user. Do you agree @karelpeeters?
    k
    • 2
    • 1
  • b

    Bernhard

    08/27/2018, 3:39 PM
    is there a nice way to get from a Set<String?> to a Set<String> then?
    s
    f
    • 3
    • 9
  • c

    coder82

    08/27/2018, 4:28 PM
    Getting this error which forces me to disable dce, why isn't dce ignoring the duplicate and going ahead?
    -.xml
    k
    • 2
    • 1
  • p

    passsy

    08/27/2018, 7:19 PM
    I have a class which implement
    MutableList<T>
    with a delegate. The class doesn’t have other properties. How can I write a working
    equals
    method which includes the delegate. Can I access it somehow?
    class WidgetListBuilder : MutableList<Widget> by mutableListOf() {
    
        inline fun <T : Widget> add(widget: T, init: T.() -> Unit): T {
            widget.apply(init)
            add(widget)
            return widget
        }
    
        override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (other !is WidgetListBuilder) return false
            // TODO handle list
            return true
        }
    
        override fun hashCode(): Int {
            return javaClass.hashCode()
        }
    }
    d
    • 2
    • 5
  • p

    pavel

    08/27/2018, 10:40 PM
    then what will happen if we do
    open class Outer {
            val inner = Inner()
            open val foo = 3
            open inner class Inner {
                val innerFoo = foo // Accessing non-final property foo in constructor
            }
        }
    ?
    k
    • 2
    • 3
  • g

    groostav

    08/27/2018, 10:42 PM
    is there a weak-reference ReadWriteProperty built-in to kotlin?
    k
    l
    • 3
    • 4
  • k

    karelpeeters

    08/28/2018, 5:55 AM
    There's
    fold
    for things like that.
    s
    e
    m
    • 4
    • 13
  • n

    no

    08/28/2018, 8:24 AM
    i think this is the repo: https://github.com/Kotlin/kotlin-koans-edu
    👍 1
    f
    • 2
    • 1
  • j

    jakub.dyszkiewicz

    08/28/2018, 9:29 AM
    Hi, this may be strange question. Where can I find
    String#toString
    implementation? I can see in Java
    public String toString() {
            return this;
        }
    but I can’t see this in Kotlin.
    public class String : Comparable<String>, CharSequence {
        companion object {}
        
        /**
         * Returns a string obtained by concatenating this string with the string representation of the given [other] object.
         */
        public operator fun plus(other: Any?): String
    
        public override val length: Int
    
        public override fun get(index: Int): Char
    
        public override fun subSequence(startIndex: Int, endIndex: Int): CharSequence
    
        public override fun compareTo(other: String): Int
    }
    I can’t find extension function either…
    k
    • 2
    • 1
  • d

    Dominaezzz

    08/28/2018, 7:19 PM
    Is there a reason we have binary functions instead of operators? Like
    shr
    ,
    shl
    ,
    and
    and
    or
    instead of
    >>
    ,
    <<
    ,
    &
    and
    |
    ?
    n
    g
    s
    • 4
    • 17
  • l

    lifter

    08/28/2018, 8:12 PM
    It seems a bit odd that I'm required to explicitly state the return type of
    Nothing
    in this case...
    fun justThrowIt(): Nothing = throw IOException()
    ...while here, I'm not:
    fun justLoop() { while (true) {} }
    d
    a
    • 3
    • 29
  • l

    lifter

    08/28/2018, 8:14 PM
    If I do add it, as in
    fun justLoop(): Nothing { while (true) {} }
    , the code does compile.
    d
    • 2
    • 4
  • w

    wei

    08/29/2018, 2:37 AM
    I have an abstract class
    A
    that has an abstract member property defined by an interface:
    interface Tool {
      fun run(command: String): Boolean
    }
    
    abstract class A {
      abstract protected var tool: Tool
      fun execute(command: String) : Boolean {
        return tool.run(command)
      }
    }
    Then I have another class
    B
    that inherits from
    A
    and uses guice to inject the
    tool
    member property at startup.
    class B {
      @Inject
      @Transient
      override protected var tool: Knife
    }
    where
    Knife
    is a concrete class implementing the interface
    Tool
    . Intellij is complaining to me:
    Var property tye is `Knife`, which is not a type of overridden protected abstract var tool: Tool defined in com.myorg....
    .
    a
    • 2
    • 1
  • a

    adam-mcneilly

    08/29/2018, 1:22 PM
    The
    assertFalse
    function in Kotlin test requires a non null boolean. What is the most idiomatic way to handle a nullable boolean?
    assertFalse(condition ?: true)
    is one. We could also invert it and say
    assertTrue(condition == false)
    but honestly I wish I could just pass a nullable boolean. I'm not sure why we couldn't.
    s
    g
    • 3
    • 2
Powered by Linen
Title
a

adam-mcneilly

08/29/2018, 1:22 PM
The
assertFalse
function in Kotlin test requires a non null boolean. What is the most idiomatic way to handle a nullable boolean?
assertFalse(condition ?: true)
is one. We could also invert it and say
assertTrue(condition == false)
but honestly I wish I could just pass a nullable boolean. I'm not sure why we couldn't.
s

spand

08/29/2018, 1:26 PM
I would prefer the latter of the two. Maybe its because I use hamkrest where its just
assertThat(condition, equalTo(false))
👍 1
g

gildor

08/29/2018, 5:49 PM
You can define own assertFalse that concider null as false, if it make sense for your usecase. But it shouldn't be default behavior Also official style guide recommends to use == instead of ?: for nullable booleans
View count: 1