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

    dumptruckman

    06/30/2017, 3:35 PM
    I have a class overriding Exception that I converted from Java. IDEA is yelling at me about this
    override fun getMessage(): String {
            return super.message
        }
    It says 'getMessage' overrides nothing
    a
    • 2
    • 4
  • d

    dineshbob

    07/01/2017, 5:02 AM
    Hi all. How can I create a List with initial capacity in Kotlin similar to Java? It seems the mutableListOf method only has elements parameter.
    v
    j
    m
    • 4
    • 20
  • j

    jschneider

    07/01/2017, 9:28 AM
    Hey guys. What is the reasoning behind using the colon (":") to call the primary constructor from a secondary constructor? In other cases the ":" colon separates the type (parameter) or return type. This seems to be a little bit inconsistent for me (as a Java dev). Any explanation for that?
    k
    • 2
    • 3
  • v

    voddan

    07/01/2017, 9:43 AM
    I spotted a weird SO question about an inconsistency in the type system https://stackoverflow.com/q/44857715/3144601 Is it a bug or a feature? Type system gurus? @dmitry.petrov, @yole?
    l
    d
    • 3
    • 2
  • a

    akerenyi

    07/01/2017, 3:50 PM
    Hi, I wanted to ask this on the #koans channel, but it seems to be quite inactive. I’m trying to install the IntelliJ Kotlin Educational Plugin, but it does not show up when browsing the repositories. Any idea what am I doing wrong?
    o
    r
    • 3
    • 2
  • k

    karelpeeters

    07/01/2017, 6:45 PM
    Is there a way to make a write-only property? Just leaving out the getter doesn't work, and having it throwing an exception isn't a compile-time error.
    l
    • 2
    • 4
  • s

    sitepodmatt

    07/03/2017, 6:41 AM
    @karelpeeters that works. took me a while too see how in your example as im used to explicit this/self. just thinking how a golang defer would be nice in this example { defer { this.started = true}(); return !this.started } .. obv this all just trivial somewhat pointless examples as I get to grips with Kotlin conventions (or lack of them)
    k
    • 2
    • 1
  • t

    thisen

    07/03/2017, 6:49 PM
    I'm confused about when to use extension functions. Take this example in Ktor: https://github.com/Kotlin/ktor/blob/master/ktor-core/src/org/jetbrains/ktor/http/ContentTypes.kt It contains the ContentType class, but at line 120, this extension function is right next to the class:
    fun ContentType.withCharset(charset: Charset) = withParameter("charset", charset.name())
    Why isn't it placed inside the class?
    d
    • 2
    • 4
  • k

    karelpeeters

    07/04/2017, 7:37 AM
    Just press CTRL+ALT+L every so often
    👌 2
    v
    • 2
    • 2
  • e

    elect

    07/04/2017, 11:07 AM
    after two weeks, updating everything to
    1.2-M1
    and now top level parameters and functions are invisible from gradle dependencies projects.. what happens? anyone experienced anything similar?
    v
    • 2
    • 3
  • k

    karelpeeters

    07/04/2017, 7:52 PM
    @tipsy Please post your entire code so we can see what going on.
    t
    i
    • 3
    • 6
  • d

    dierre

    07/05/2017, 8:10 AM
    Hello, what would be the industry solution to do mocking in Kotlin?
    a
    • 2
    • 1
  • k

    kirillrakhman

    07/05/2017, 8:11 AM
    final by default might become a problem, but if you code against interfaces that shouldn't be a problem
    r
    • 2
    • 2
  • j

    jschneider

    07/05/2017, 5:52 PM
    I'd say: If you have to use the class from Java a builder seems to be the best idea...
    ➕ 1
    n
    g
    • 3
    • 4
  • r

    rockerhieu

    07/06/2017, 2:21 AM
    I have this method:
    fun click(onClick: ((v: View) -> Unit)? = null) {}
    What is the correct syntax for describing
    click(if (condition) null else <a lambda>)
    v
    f
    • 3
    • 15
  • r

    rajendhiraneasu

    07/06/2017, 12:42 PM
    hi guys, just i'm a beginner to kotlin progra, any one can explain what is the difference between abstract and interface in kotlin?
    m
    d
    • 3
    • 12
  • d

    dierre

    07/06/2017, 3:47 PM
    Hello, it’s still me. Small question I can’t seem to solve by myself. I’ve put in a project which is used as a parent by another maven project this extension function:
    fun RestClientBuilder.withKotlinSupport(): RestClientBuilder {
        KotlinRestClientFactoryConfigurer.configure(this)
        return this
    }
    Now this class just adds the KotlinModule for Jackson. The problem is that if I build my
    RestClient
    with the
    RestClientBuilder
    on the child project, there is no way I can see
    withKotlinSupport
    . Could you tell me a way to identify which is the problem?
    k
    • 2
    • 31
  • k

    kaiyang.tay

    07/06/2017, 4:02 PM
    For one example, i tried to understand function as first class citizen etc, which generally still can be digested. But i do not get it when FP try to advocate people to avoid null, be null safe etc. But yet kotlin has ? To define a nullable variable. This seems to give me a conflicting measage.
    k
    • 2
    • 1
  • e

    elect

    07/06/2017, 4:04 PM
    is it possible to
    continue
    the
    while
    if I have something like:
    while(..) {
       x?.let{ ... if(y) continue }
    ?
  • p

    poohbar

    07/06/2017, 6:49 PM
    it does know the return type if you specify the lambda type explicitly, right?
    d
    • 2
    • 1
  • k

    karelpeeters

    07/07/2017, 2:58 PM
    @poohbar I once managed to build & run "Hello World" using javac, then I tried gradle and never looked back. Don't tell me there are people that actually compile their code manually?
    p
    f
    +3
    • 6
    • 11
  • j

    jschneider

    07/08/2017, 9:35 AM
    Hey. Anybody can help me with java interoperability? I want to call a method with a wildcard list from java Kotlin method I want to call:
    class DaClass {
      companion object {
        @JvmStatic
        fun convert(strings: Iterable<String>): List<Int> {
          return strings.map { convert(it) }
        }
    
        @JvmStatic
        fun convert(string: String): Int {
          return java.lang.Integer.parseInt(string)
        }
      }
    }
    Java-Call:
    List<String> list = ImmutableList.of("1", "2");
        System.out.println(DaClass.convert(list));
    
        List<? extends String> listWithWildcards = ImmutableList.of("1", "2");
        System.out.println(DaClass.convert(listWithWildcards)); //Does *not* compile
    t
    • 2
    • 3
  • d

    diesieben07

    07/08/2017, 10:44 AM
    No, you'd have to make a factory method then and make the constructor private, which means you also need to override
    copy
    . If you use
    invoke
    in the companion object, you can make it look like a normal constructor call though.
    j
    • 2
    • 5
  • d

    danneu

    07/08/2017, 4:30 PM
    the Gradle project wizard seems to gen src folder if you tick the "leave empty folders" box -- don't remember the wording
    k
    • 2
    • 1
  • k

    karelpeeters

    07/08/2017, 9:53 PM
    @jschneider The same thing:
    enum class Test {
        A, B, C
    }
    
    val a = Test.valueOf("A")
    j
    • 2
    • 3
  • j

    jschneider

    07/08/2017, 10:07 PM
    And one more thing. How to throw a generic type:
    public <E extends Throwable> void foo() throws E
    k
    • 2
    • 3
  • o

    orangy

    07/08/2017, 10:55 PM
    The problem looks like functional type is nullable, so you can’t just call it with
    ()
    . Either check it for null, or use safe call with explicit invoke
    k
    • 2
    • 1
  • q

    qwasz

    07/09/2017, 2:54 AM
    Anyone recommend any ebooks to start off with?
    v
    • 2
    • 1
  • m

    menegatti

    07/10/2017, 7:33 AM
    would an interface with those 3 fields work for you?
    n
    m
    • 3
    • 15
  • v

    veiset

    07/10/2017, 11:28 AM
    Hey! I am trying to understand how the type def of
    getOrElse
    works.
    fun foo(x: String) : () -> String  = { x + "!" }
    
    val map = mapOf(Pair("a", 1), Pair("b", 2))
    val result = map.getOrElse("x", foo("kotlin"))
    I would expect a type-error here, but it happily returns a String. If I define the type of
    result
    it works as I would expect. Can someone help me understand the type definition of `orGetElse`:
    public inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: () -> V): V = get(key) ?: defaultValue()
    m
    d
    • 3
    • 8
Powered by Linen
Title
v

veiset

07/10/2017, 11:28 AM
Hey! I am trying to understand how the type def of
getOrElse
works.
fun foo(x: String) : () -> String  = { x + "!" }

val map = mapOf(Pair("a", 1), Pair("b", 2))
val result = map.getOrElse("x", foo("kotlin"))
I would expect a type-error here, but it happily returns a String. If I define the type of
result
it works as I would expect. Can someone help me understand the type definition of `orGetElse`:
public inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: () -> V): V = get(key) ?: defaultValue()
m

menegatti

07/10/2017, 11:29 AM
veiset: unrelated, but do you know that you can do
"a" to 1
, instead of creating a new
Pair
?
d

diesieben07

07/10/2017, 11:29 AM
The
V
in
Map
is an
out
parameter, so really the signature is
public inline fun <K, V> Map<K, out V>.getOrElse...
v

veiset

07/10/2017, 11:30 AM
Oh, I didn't know that Edson. That's pretty sweet. Thanks!
d

diesieben07

07/10/2017, 11:30 AM
V
is inferred to be
Any
and then you have a
Map<K, out Any>
, which your map satisfies.
v

veiset

07/10/2017, 11:31 AM
Oh. That makes sense. How do I see that the signature really is
Map<K, out V>
? Do I have to check the signature of
Map
?
Yup. You do.
d

diesieben07

07/10/2017, 11:32 AM
Yes. Declaration-Site variance is the keyword here.
v

veiset

07/10/2017, 11:32 AM
Thanks Take! Perfect, now I understand. Cheers. 😄
View count: 3