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

    oday

    01/31/2018, 12:09 PM
    how does this translate into Kotlin?
    linearLayoutManager = new LinearLayoutManager(context) {
     @Override
     public boolean canScrollVertically() {
      return false;
     }
    };
    t
    • 2
    • 3
  • r

    Ruckus

    01/31/2018, 11:24 PM
    val description = descriptionTextView.text.toString().takeUnless { it.isBlank() } ?: "A DefaultString"
    🤔 1
    👍 7
    i
    • 2
    • 1
  • p

    poohbar

    02/01/2018, 4:34 PM
    you could do:
    val (one, two, three) = listOf(0,  0, 0)
    😄
    😬 4
    a
    o
    • 3
    • 3
  • k

    kevinmost

    02/01/2018, 5:23 PM
    that'd be slightly better (but still terrible IMO) as
    val (one, two, three) = IntArray(3) { 0 }
    a
    • 2
    • 7
  • o

    oday

    02/01/2018, 7:54 PM
    meaning…I only that there is only going to be 1 result out of my filter, it’s not a map
    i
    • 2
    • 1
  • s

    Slackbot

    02/01/2018, 8:59 PM
    This message was deleted.
    s
    e
    • 3
    • 2
  • o

    oday

    02/02/2018, 10:47 AM
    val statusMap = mutableMapOf(
                noreply to 0, contacted to 0, finished to 0,
                negotiating to 0, sold to 0, notContacted to 0
            )
    
            searchResults.forEach {
                if (statusMap.containsKey(it.state)) {
                    statusMap[it.state] = statusMap.getValue(it.state) + 1
                }
            }
    l
    • 2
    • 1
  • a

    Athul Antony

    02/03/2018, 12:50 PM
    http://www.techeos.com/posts/android-kotlin-tricks.html
    🚓 4
    k
    d
    • 3
    • 2
  • e

    Eleos

    02/04/2018, 11:35 AM
    Can someone link me a good Kotlin guide or tutorial? The Kotlin Koans are more confusing than helping..
    a
    • 2
    • 1
  • k

    kef

    02/05/2018, 7:47 PM
    Hi guys. I want do do some basic stuff and I’m stuck. What’s the fastest way to do convert:
    val a = listOf(Pair("a", 1), Pair("a", 2), Pair("b", 1))
    into:
    [(a, 3), (b, 1)]
    So, just group by key and sum values Best I can do is:
    a.groupBy ({ it.first}, {it.second} ).map{(key, value) -> key to value.sum()}
    but there must be better way
    r
    • 2
    • 5
  • k

    kef

    02/05/2018, 8:31 PM
    @ibcoleman tbh I’m looking for both, something like:
    a.groupByKey{(x,y) -> x+y}
    where
    x
    and
    y
    are values from pairs with identical keys, but I understand there is no such method in std library
    i
    k
    i
    • 4
    • 4
  • h

    hho

    02/06/2018, 1:40 PM
    I have Java code which uses
    object.wait()
    and
    object.notify()
    . What's the best way to convert this to Kotlin? The converter in IntelliJ replaces
    Object
    with
    Any?
    , but
    wait()
    and
    notify()
    are of course not defined on
    Any
    .
    n
    e
    • 3
    • 4
  • b

    Bob

    02/06/2018, 5:29 PM
    Is there a way to get the
    it
    single lambda parameter paradigm working in the context of what I guess would be an anonymous lambda? For a trivial example:
    kotlin
    val test: Pair<String, (String) -> Boolean> = "length is 6" to { input -> input.length == 6 }
    Is there a way I can get the implicit
    it
    parameter in there?
    r
    • 2
    • 3
  • k

    karelpeeters

    02/06/2018, 6:31 PM
    @Bob I think you're running into this issue: https://youtrack.jetbrains.com/issue/KT-12833
    b
    • 2
    • 3
  • c

    cedric

    02/07/2018, 7:45 AM
    Use
    ?.let
    , not
    .let
    s
    • 2
    • 2
  • c

    chb0kotlin

    02/09/2018, 6:14 AM
    It's basically for compatibility with hibernate - if I make a class like this:
    @Entity
    data class Form(@Id @GeneratedValue override var id: Long? = null,
                    override var date: Date? = null,
                    override var name:String? = null) : Post
    Then, it's good. Except, I now have setters
    k
    • 2
    • 1
  • s

    scap

    02/09/2018, 7:05 AM
    @chb0kotlin Could this work?
    class Foo internal constructor() {
        var bar: Int = 0
        private set
    
        var fuz: String = ""
        private set
    
        constructor(a: Int, b: String) : this(){
            this.bar = a
            this.fuz = b
        }
    }
    
    var foo = Foo(9,"hello world")
    c
    • 2
    • 1
  • j

    juhanla

    02/09/2018, 11:18 AM
    So i have an abstract class and two classes that extend it. I have two lists of the abstract class. with union function they all seem to be unique even if i override equals function to return true on the absract class and both of the extending classes. Anyone have a clue why is that?
    m
    • 2
    • 4
  • s

    Shawn

    02/10/2018, 4:07 AM
    also kinda wondering what you’re using
    KCallable
    for
    j
    • 2
    • 6
  • b

    bloder

    02/10/2018, 4:07 AM
    Isn't worth for you init in lazy block? ( I didn't test this solution )
    class ExampleClass(private val targetClass: KClass<*>, private val solution: KCallable<*>) {
    
        private val studentMethod by lazy {
            var methodFinding: KCallable<*>? = null
            for (m: KCallable<*> in targetClass.declaredMembers) {
                if (m.name == solution.name && (methodFinding == null || validateParameterTypes(m))) {
                    methodFinding = m
                }
            }
            methodFinding
        }
    
        private fun validateParameterTypes(m: KCallable<*>): Boolean { ... }
    }
    j
    • 2
    • 1
  • r

    rellenberger

    02/12/2018, 7:08 PM
    Is there a way to lock down a sealed class to prevent extensions on it?
    r
    • 2
    • 1
  • k

    Kenneth

    02/12/2018, 10:32 PM
    @Configuration
    class MetricsConfig {
       @Bean
       fun commonTags(): MeterRegistryCustomizer<MeterRegistry> = { registry ->    
          registry.config().commonTags("kenneth", "kenneth2")
       }
    }
    Gives:
    Inferred type is a function type, but a non-function type MeterRegistryCustomizer<MeterRegistry> was expected. Use either '= ...' or '{ ... }', but not both
    d
    a
    • 3
    • 9
  • a

    adalbert

    02/13/2018, 6:05 PM
    Hi, I've started with kotlin few days ago, and I got a question about smart cast in custom equals implementation (I know there are data classes in kotlin, just asking about this specific case) IDE can generate this kind of equals
    override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (javaClass != other?.javaClass) return false
    
            other as Model
    
            if (name != other.name) return false
            if (lastName != other.lastName) return false
            if (password != other.password) return false
    
            return true
        }
    We can change it to this
    override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (javaClass != other?.javaClass) return false
    
            other as Model
    
            return name == other.name
                    && lastName == other.lastName
                    && password == other.password
    
        }
    And my question is if this possible to get rid of all ifs? Why, why not?
    override fun equals(other: Any?): Boolean {
            return this === other
                    || javaClass == other.javaClass
                    && name == other.name
                    && lastName == other.lastName
                    && password == other.password
        }
    If this post is too long i will try to shrink it
    r
    • 2
    • 11
  • s

    scap

    02/13/2018, 9:07 PM
    @dalexander I didn't think objects could have a default parameter
    d
    m
    • 3
    • 2
  • c

    chb0kotlin

    02/14/2018, 6:59 AM
    can Someone explain to be what this compiler error is telling me and how to fix it?
    interface AclClassRepository : PagingAndSortingRepository<AclClass, Long>
    @Component
        class SecurityConfiguration(private val classRepo: AclClassRepository) : WebSecurityConfigurerAdapter() {
    
            @PostConstruct
            private fun init() {
                val context = SecurityContextHolder.getContext()
                context.authentication = UsernamePasswordAuthenticationToken("system", "system",
                        createAuthorityList("ROLE_ADMIN"))
    
    
                val all = classRepo.findAll()
                val reflections = Reflections(this.javaClass.`package`.name)
    
                val entities = all - reflections.getTypesAnnotatedWith(Entity::class.java)
    
               // Error:(64, 42) Kotlin: Type parameter bound for S in fun <S : AclClass!> save(p0: S): S
     is not satisfied: inferred type Any! is not a subtype of AclClass!
    
                entities.forEach { classRepo.save(it) }
    
    //Error:(65, 23) Kotlin: Type parameter bound for S in fun <S : AclClass!> saveAll(p0: (Mutable)Iterable<S!>): (Mutable)Iterable<S!>
     is not satisfied: inferred type Any! is not a subtype of AclClass!
    
                classRepo.saveAll(entities)
    
    
                SecurityContextHolder.clearContext()
    
            }
    }
    m
    r
    • 3
    • 2
  • k

    karelpeeters

    02/15/2018, 8:35 AM
    @Ajith Now that is a strange error... Can you
    ctrl+Q
    on the parameters to double-check their types?
    a
    • 2
    • 2
  • k

    karelpeeters

    02/15/2018, 8:35 AM
    fun turnOn() { state = true }
    right, assignments aren't expressions.
    m
    • 2
    • 1
  • l

    laht

    02/15/2018, 12:19 PM
    this question has probably been asked before, but why can we not write val value: Double = 5d like in Java? For floats we can use f.
    d
    • 2
    • 1
  • v

    Vesko Vujovic

    02/15/2018, 2:52 PM
    I can hardly find on official spring security documentation what i want. Thanks in advance.
    d
    • 2
    • 1
  • e

    edhu

    02/15/2018, 5:32 PM
    hi, i am using IntelliJ. I have a
    fun main()...
    function that I execute. when I execute the main function, the program runs, but I know there are exceptions being thrown by my code but none get outputted to my console. How can I setup logging so that I can see the logs in the console?
    f
    d
    • 3
    • 28
Powered by Linen
Title
e

edhu

02/15/2018, 5:32 PM
hi, i am using IntelliJ. I have a
fun main()...
function that I execute. when I execute the main function, the program runs, but I know there are exceptions being thrown by my code but none get outputted to my console. How can I setup logging so that I can see the logs in the console?
f

fred.deschenes

02/15/2018, 5:53 PM
Well it depends on where those exceptions are thrown and what logging framework you use
e

edhu

02/15/2018, 6:02 PM
Hi,i'm using:
io.github.microutils:kotlin-logging:1.4.9
if i log statements in my project, it works. but the exceptions being thrown from a Jar dependency that i call do not get shown in the console
all i see is
Process finished with exit code 0
f

fred.deschenes

02/15/2018, 6:22 PM
you'll have to check what logging framework this dependency uses and probably change some configs on your side to have their loggers show up in your log files/IDE (I've never used kotlin-logging so I don't really know how it works)
what's your dependency that's throwing the exception?
e

edhu

02/15/2018, 6:23 PM
my own jar file
in my own jar file, i added:
compile 'org.slf4j:slf4j-api:1.7.10'
i read that for libraries, i only have to add that dependency
f

fred.deschenes

02/15/2018, 6:25 PM
yeah but you still have to log whatever you want logged yourself
e

edhu

02/15/2018, 6:26 PM
the exception not being logged is a NPE because some models are not marked as nullable
i'm an Android developer, and I'm used to every error is shown in the console
i guess it is a system exception, Kotlin telling me a property is not set as nullable
f

fred.deschenes

02/15/2018, 6:30 PM
yeah NPEs are RuntimeExceptions
e

edhu

02/15/2018, 6:30 PM
what can i do to show all these errors in the console?
f

fred.deschenes

02/15/2018, 6:31 PM
either way, you won't see exceptions show up in the console if they aren't : 1: thrown in the main thread 2: explicitly logged in some logging framework
so you'd have to get a logger from SLF4J, wrap whatever is throwing your exception in a try/catch and do
logger.error(...)
with your caught exception
e

edhu

02/15/2018, 6:35 PM
ok, so i run the code and on a breakpoint before the NPE i can see : "ForkJoinPool.commonPool-worker-1" in group "main" : RUNNING
so it is in the main thread
i just wrapped the call in a try catch but nothing is shown
f

fred.deschenes

02/15/2018, 6:39 PM
if your thread name is "ForkJoinPool.commonPool-worker-1" you're definitely not in the main thread
either way I suggest you read a bit on how SLF4J works as you'll have other stuff to setup to make sure your logs are displayed correctly (if at all) : https://www.slf4j.org/docs.html
e

edhu

02/15/2018, 6:42 PM
ok thanks.
removed the code from the background thread and now i'm seeing what i expected
indeed, it was not in the main thread
f

fred.deschenes

02/15/2018, 6:46 PM
yeah that's what I figured 😉
and don't worry, no one understands the Java logging frameworks at first (still not sure I really understand either >_>)
d

dave08

02/16/2018, 3:47 AM
Use
runBlocking
and
await
or
join
. CommonPool is the default thread pool dispatcher in coroutines... you need to wait for the result to come back from the thread...
e

edhu

02/16/2018, 10:20 AM
@dave08 thanks. did that and it also works
View count: 2