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

    tschuchort

    12/22/2018, 6:23 PM
    For some reason I can't use Java classes from my Kotlin files in IntelliJ (with Gradle). Using Kotlin from Java is fine but when I try to use a Java class it reports unresolved reference. The import quickfix of course appears but doesn't do anything. Any ideas what the problem could be? (The classes are all in the test module in case that matters)
    g
    • 2
    • 4
  • g

    ghedeon

    12/22/2018, 11:07 PM
    It's not that uncommon tho. You have a set of items that share common properties and differ by one field. The result of modeling this will be quite chatty.
    🤔 1
    g
    a
    • 3
    • 4
  • s

    SrSouza

    12/22/2018, 11:40 PM
    Hi guys, i want to know if has something in contracts that make this works
    c
    • 2
    • 2
  • o

    otakusenpai

    12/23/2018, 7:29 AM
    can anyone tell me how to navigate this 2d array:
    var board = Array(row,{IntArray(col)})
    g
    f
    • 3
    • 3
  • r

    Rohan Maity

    12/23/2018, 12:48 PM
    I published Tail Call optimization in JVM with Kotlin . JVM doesn't support Tail Call optimization. But with Kotlin you can write Tail Call optimised way . This article also tells how Kotlin does this https://medium.com/@rohanmaity/tail-call-optimization-in-jvm-with-kotlin-ebdf90b34ec9
    c
    • 2
    • 2
  • j

    jdemeulenaere

    12/23/2018, 4:24 PM
    Is there any library/annotation processor out there that generates code to read some configuration bean from environment & command line args ? Something similar to @ConfigurationProperties in Spring but at compile time. I know Micronaut does something like that but I don't think there is a separate library that I can just use on a non micronaut project.
    c
    • 2
    • 1
  • j

    Joris PZ

    12/23/2018, 8:15 PM
    Is this behaviour documented anywhere? Why does reallyReallyReallyLong become zero? Does the result after multiplication simply get truncated to 64 bits?
    d
    e
    • 3
    • 5
  • d

    dave08

    12/24/2018, 11:59 AM
    Is this a Kotlin related error (I'm getting it in the Intellij Ultimate debugger evaluator while running a Kotlin expression using a Java lib), and what could this be:
    An exception occurs during Evaluate Expression Action : com.sun.tools.jdi.ClassTypeImpl cannot be cast to com.sun.jdi.ArrayType
    ?
    k
    • 2
    • 1
  • r

    rrader

    12/24/2018, 1:08 PM
    How can I find what intrinsics are included in construtor to check if is not-null?
    c
    • 2
    • 2
  • r

    robinchew

    12/24/2018, 8:17 PM
    Hi there, if I have the following code:
    val f: (Context) -> View = ::TextView
            val text = f(activity)
    how do I check that
    text
    is an 'instance' of
    f
    ?
    a
    v
    d
    • 4
    • 37
  • o

    octylFractal

    12/25/2018, 12:15 AM
    is there a bug with kapt and
    abstract var
    properties? I have this:
    sealed class Tag<T> { // note: TagId/SongId classes are inline
        abstract var id: TagId
        abstract var songId: SongId
        abstract var data: T
    }
    but it only generates a setter for
    data
    . the other two only have getters
    o
    • 2
    • 4
  • k

    king_marquant

    12/25/2018, 3:09 AM
    Can I get help with pdfs I can start with to learn kotlin... Many thanks.. 😃
    d
    r
    • 3
    • 2
  • k

    karelpeeters

    12/25/2018, 11:06 AM
    First: yes, the Java class your extension functions end up in will change name. Second: no, those generics are erased anyway.
    s
    g
    • 3
    • 5
  • d

    Dico

    12/25/2018, 11:43 AM
    You can specify the java class name associated with the file using a file annotation
    s
    • 2
    • 2
  • c

    Czar

    12/25/2018, 12:41 PM
    Is there a nice pattern to avoid unnecessary null checks, like following?
    @Entity class MyEntity(val id: Long?, ...)
    val myEntity = myEntityRepository.getById(1L)
    // fun useMyEntityId(id: Long) {...}
    useMyEntityId(checkNotNull(myEntity.id)) // check here is logically unnecessary, since entity retrieved from database will always have id
    I'm asking in general, but if there is anything specific for Spring Boot and Hibernate, that would be also interesting.
    • 1
    • 1
  • k

    karelpeeters

    12/25/2018, 12:58 PM
    The other way to express this is with generics,
    class Entity<D: Int?>(val id: D)
    and then keep the nullability in the type throughout the code.
    c
    • 2
    • 4
  • c

    Czar

    12/25/2018, 12:59 PM
    yes, id is null before entity is persisted, but when retrieved from repository, that is impossible. So far I came up with this design:
    @Entity
    class MyEntity {
    	@Id
    	private val _id: Long? = null
    	@Transient
    	val id: Long
    		get () = checkNotNull(_id) { "Should not try to retrieve ID of an entity before it is persisted" }
    }
    p
    • 2
    • 2
  • c

    Czar

    12/25/2018, 1:05 PM
    lateinit
    doesn't work with primitive types anyway
    k
    • 2
    • 2
  • d

    Dico

    12/25/2018, 4:13 PM
    Man, just add a boolean flag. The entity stuff is just way overcomplicating.
    var hasId: Boolean = false
    var id: Long = 0L
      get() = TODO()
    c
    • 2
    • 3
  • o

    octylFractal

    12/25/2018, 7:07 PM
    It says in the kapt documentation: "Note that Kapt does not support multiple rounds for the generated Kotlin files." Does this mean that annotation processing won't run on them at all? Or that it will just happen once
    • 1
    • 2
  • c

    Czar

    12/26/2018, 8:26 AM
    Quick poll when you know for sure that something is not null, while it appears nullable, which construct should you use? 1️⃣ checkNotNull(something) 2️⃣ something!! If you have an explanation for your preference I encourage you to post it as a thread comment. Example:
    // hibernate is used for illustration, because it recommends to use nullable IDs for entities
    val entity: MyEntity = hibernateRepository.requireEntityById("some-id")
    private fun String.doSomethingWithId()
    // 1
    checkNotNull(entity.id).doSomethingWithId()
    // 2
    entity.id!!.doSomethingWithId()
    1️⃣ 2
    2️⃣ 5
    l
    g
    +3
    • 6
    • 29
  • g

    gildor

    12/26/2018, 8:27 AM
    One more thing which I use more often than 1:
    val entity = hibernateRepository.getEntityById("some-id") ?: error("some-id is null")
    ➕ 1
    c
    • 2
    • 4
  • m

    marcinmoskala

    12/26/2018, 8:36 AM
    How do I get
    KClass
    from
    KType
    ?
    c
    • 2
    • 2
  • j

    jgodort

    12/26/2018, 12:27 PM
    Hi all!! anyone could help me? what is the meaning of ! in a function param declaration? like this fun foo(param:String!)
    d
    g
    +2
    • 5
    • 6
  • m

    Matt Spain

    12/26/2018, 3:15 PM
    Is there a size limit to shareable snippets in the Kotlin playground? I'm getting nothing when I try to generate a sharing link.
    r
    l
    • 3
    • 3
  • a

    Andrew Gazelka

    12/26/2018, 6:00 PM
    https://gist.github.com/andrewgazelka/b8170e452fa3dd0c0fb6d3875dc502ee think it is appropriate to have
    getMemoryUsed()
    outside the class as it functions as a util fun?
    h
    • 2
    • 2
  • a

    Andrew Gazelka

    12/27/2018, 3:01 AM
    ummmmm
    d
    b
    • 3
    • 9
  • o

    otakusenpai

    12/27/2018, 4:25 AM
    so I'm making a chess game and I've got the Rook and pawn's move function ready but I'm having some problem with the Knight's move function.
    for(m in 0..(8-x))
                            for(n in 0..(8-y)) {
                                if(board.board[m][n].group != this.group) {
                                }
                            }
    All I want is that the 2d array should have the ability to increase or decrease its row and column....without a for loop. Thnx
    p
    g
    • 3
    • 3
  • h

    hhariri

    12/27/2018, 10:46 AM
    <!here> Thank you all for taking part in nominating the Most Helpful Slack Member. The final nominees are below. Please vote for your candidate using the corresponding number (you can only vote for a single candidate). Voting ends 28th December 12 pm CET. 1. @gildor 2. @jw 3. @louiscad 4. @karelpeeters 5. @Shawn 6. @kpgalligan 7. @thomasnield 8. @edvin 9. @irus 10. @raulraja
    5️⃣ 5
    8️⃣ 6
    2️⃣ 37
    1️⃣ 59
    4️⃣ 14
    6️⃣ 6
    7️⃣ 6
    🔟 40
    3️⃣ 39
    9️⃣ 2
    g
    r
    +2
    • 5
    • 7
  • x

    xenoterracide

    12/27/2018, 6:20 PM
    is there a more idiomatic way to write this?
    repositories =  modules.map { it to "<mailto:git@bitbucket.org|git@bitbucket.org>:my/${it}.git" } .toMap()
    m
    t
    s
    • 4
    • 5
Powered by Linen
Title
x

xenoterracide

12/27/2018, 6:20 PM
is there a more idiomatic way to write this?
repositories =  modules.map { it to "<mailto:git@bitbucket.org|git@bitbucket.org>:my/${it}.git" } .toMap()
m

mkobit

12/27/2018, 6:26 PM
associateBy
? - https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/associate-by.html
oh nvm someone already answered
t

todd.ginsberg

12/27/2018, 6:36 PM
Kotlin 1.3 has
associateWith
that makes this nicer...
repositories = modules.associateWith { "<mailto:git@bitbucket.org|git@bitbucket.org>:/my$it.git"}
s

Steven McLaughlin

12/27/2018, 6:36 PM
Does that just associate
it
with whatever is in that lambda?
t

todd.ginsberg

12/27/2018, 6:45 PM
Yes
👍 1
View count: 1