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
language-proposals
  • p

    pakoito

    10/14/2017, 12:01 PM
    I have watched a video about Swift where it’s explained that structs with just one basic type (numbers/string) is optimized away at compile time to be represented by just that basic type. This allows the creations of thin wrappers.
    r
    • 2
    • 2
  • a

    artem_zin

    10/15/2017, 6:57 AM
    I have unfinished KEEP "Inline classes" which covers this simple scenario of single field type-safe alias with requirements (extension functions, cross-module visibility, Java non-visibility, etc), use cases and possible syntax constructions, @dmitry.petrov should I post it as a PR to KEEP so community could discuss it, find issues and solutions or it's something we should wait for?
    k
    d
    • 3
    • 5
  • r

    raulraja

    10/24/2017, 8:07 PM
    Since it works at compile time it would work for those types for which you declare a
    Reified
    instance. For example:
    package foo
    interface Reified<A> {
        val selfClass: KClass<A>
    }
    package bar
    object ReifiedString: Reified<String> {
        val selfClass: KClass<String> = String::class
    }
    import bar.ReifiedString
    
    fooTC<String>() // compiles and returns String::class
    fooTC<Int>() // Does not compile because the compiler can't find evidence of `Reified<Int>` imported in scope
    i
    m
    • 3
    • 62
  • d

    dmitry.petrov

    10/26/2017, 3:28 PM
    There's a "library solution" for
    typeOf<T>()
    that will get you a generic JVM type, but it'd cost a class file for each call site at the moment. --- That's getKType from the gist above ;)
    m
    p
    • 3
    • 2
  • d

    dmitry.petrov

    10/26/2017, 3:36 PM
    Type literals might actually require some special syntax:
    Some::type
    currently can resolve to a member reference for
    Some.type
    e
    k
    k
    • 4
    • 4
  • m

    mbstavola

    10/26/2017, 5:46 PM
    Would it be possible to have a plugin similar to all open and no-arg, but for void return types? That is to say, if a function has the signature
    fun foo(): Unit
    it'd become
    void foo()
    in Java rather than
    Unit foo()
    when given a particular annotation. I think it'd make calling Kotlin code from Java a bit more pleasant.
    👍 1
    k
    • 2
    • 2
  • m

    mbstavola

    10/28/2017, 2:13 AM
    Was it on a public forum of some kind where I can follow discussion?
    j
    • 2
    • 3
  • a

    Andreas Sinz

    10/28/2017, 11:57 AM
    has there been any decent HKT proposal yet?
    k
    r
    • 3
    • 5
  • k

    kevinmost

    11/03/2017, 2:59 PM
    I know in Java, you get a warning if you do
    @Contract(pure = true)
    (an annotation from the Jetbrains annotation package), not sure if that works in Kotlin too?
    s
    • 2
    • 2
  • t

    trevjones

    11/04/2017, 7:37 PM
    I the panel last night Andrey made it should like he has reservations about implementation via delegation. Is there anywhere that discusses the reasoning for why it might be problematic? I tend to use it quite often in an attempt to reduce boilerplate around things like rx subscription management.
    v
    • 2
    • 1
  • r

    raulraja

    11/05/2017, 8:25 PM
    I'd like to keep the ball rolling with this one. Anyone here can advise as to what next steps looks like? Looks by the numbers in the PR description this could be a great lang feature welcomed by many users and it has already seen a lot of discussion and iterations over the original proposal. https://github.com/Kotlin/KEEP/pull/87
    k
    e
    • 3
    • 8
  • p

    pakoito

    11/07/2017, 7:25 PM
    is there any proposal for compile-time checked regex literals like in Node?
    t
    k
    a
    • 4
    • 4
  • k

    katz

    11/14/2017, 11:11 AM
    doesnt work
    s
    • 2
    • 21
  • k

    karelpeeters

    11/16/2017, 11:44 AM
    Wouldn't that be the same as adding a
    static
    keyword but less clear?
    v
    • 2
    • 1
  • k

    kirillrakhman

    11/16/2017, 11:52 AM
    Or maybe allow adding
    @JvmStatic
    to the companion object.
    👍🏽 4
    v
    • 2
    • 3
  • a

    arekolek

    11/19/2017, 2:09 PM
    When calling Java functions that have multiple parameteres eligible for SAM conversion, from Kotlin we can either pass lambdas for all those parameters or none of them. See for example https://stackoverflow.com/q/46542037/1916449 This makes sense, because otherwise Kotlin would have to generate 2^k synthetic functions for a Java function with k SAM-typed parameters. Instead it just generates the two extreme ones. Given the convention that if the last argument of a function is a lambda, you can place it after parentheses, wouldn't it make sense to also generate a special third synthetic variant, that accepts a lambda for the last argument if it's a SAM type?
  • e

    elect

    11/22/2017, 10:30 AM
    one small observation porting some c++ code: not having the possibility to have
    valueChanged |= whatever()
    introduced on kotlin side a bug,
    whatever()
    was never executed when
    valueChanged == true
    , (
    valueChanged = valueChanged || whatever()
    solved by flipping the or operands)
    a
    i
    • 3
    • 5
  • g

    galex

    11/23/2017, 5:52 AM
    Hello, when writing an inline fun <reified T> like the following:
    inline fun <reified T> logd(message: String) {
    if (BuildConfig.DEBUG) {
    Log.d(T::class.java.simpleName, message)
    }
    }
    If used without a specified type, the compiler will complain:
    logd("abandonAudioFocus() called") // type inference failed: Not enough information to infer parameter T in (...). Please specify explicitly.
    To fix this we need to specify the type:
    logd<PlayerManager>("abandonAudioFocus() called")
    Wouldn’t it be convenient if the compiler would infer the type of the class this code is called in in this case? Maybe with a new inline keyword ?
    g
    • 2
    • 10
  • g

    gregd

    11/29/2017, 9:24 AM
    Declaring defaults for generic type parameters - it’s a nice little feature I miss in Kotlin, e.g.:
    interface Foo<T, U = Unit, V = Unit>
    or even:
    interface Foo<T, U = Unit, V = T>
    This way, if you don’t care about some parameters, you could write:
    class Bar : Foo<Int>
    instead of:
    class Bar : Foo<Int, Unit, Unit>
    So far I’ve seen it in C++ and TypeScript, and it seems to work well. What do You think?
    ➕ 1
    g
    s
    +2
    • 5
    • 13
  • p

    poohbar

    11/30/2017, 3:54 PM
    could an alternative syntax for raw string literal be considered? this is ugly:
    str.replace(""""""", """\""""")
    how about
    str.replace(`"`, `\"`)
    b
    • 2
    • 1
  • r

    rrader

    12/01/2017, 7:52 AM
    how about
    fun main(args: Array<String>) {
        val str = "--\"--"
        println(str)
        println(str.replace("\"", "\\\""))
    }
    l
    k
    +2
    • 5
    • 6
  • b

    bob

    12/04/2017, 7:39 AM
    Claiming koltin is so concise, wouldn’t an `if?`statement qualify. So that one can write
    if?(state?.isValid)
    instead of
    if(state?.isValid == true)
    So when we have an if-statement of an nullable value we don’t have to explicitly declare the
    == true
    all the time.
    ➖ 7
    g
    a
    • 3
    • 4
  • n

    natpryce

    12/04/2017, 7:58 AM
    Whether null counts as true or false depends on the context. If I have a nullable bool, I use the Elvis operator:`if (state?.isValid ?: false) ...` or
    if (state?.isValid ?: true) ...
    g
    • 2
    • 11
  • b

    benleggiero

    12/10/2017, 2:23 AM
    We should support Implicit Member Expressions. This is something I enjoy at work with Swift, and drastically reduces boilerplate: https://stackoverflow.com/questions/47023274/what-is-the-swift-syntax-bar-called
    u
    g
    • 3
    • 6
  • l

    louiscad

    12/10/2017, 1:23 PM
    Hi, In an Android project, I want to make two methods that return a delegate, with one allowing nullable values, and the other not. It's for Fragment arguments. The idiomatic way would be to add 2MB to my app by using kotlin-reflect to check if the delegated property is nullable. Instead, I aim for the lightweight way, which makes me write two delegates, one for nullable values, another for non nullables. I wrote two functions
    arg()
    and
    'arg?'()
    (the single quotes being backticks, just Slack limitation), but the IDE says
    ?
    is not allowed in identifiers in Android projects. So I added the
    JvmName("argOfNullable")
    , but the IDE still complains, and I assume the compiler will too. So, please, could you add the ability to apply the identifier restriction only on the JVM name in the nearest Kotlin release possible?
    d
    • 2
    • 2
  • s

    shiraji

    12/11/2017, 1:52 AM
    What is the differences between this and
    static import
    ?
    :thread-please: 1
    b
    g
    • 3
    • 7
  • b

    bob

    12/12/2017, 7:31 AM
    Proposal to restrict an extension function for a
    typealias
    to that explicit
    typealias
    . Even if the compiler later removes all type aliases they could (and should?) first be enforced.
    typealias Degree = Double
    typealias Radian = Double
    
    fun Degree.toRadian():Radian = // Implementation
    fun Radian.toDegree():Degree = // Implementation
    
    fun run(degree:Degree) {
      // should only be able to call toRadian and not toDegree on this parameter.
      degree.toDegree()
    }
    g
    l
    r
    • 4
    • 7
  • m

    mikehearn

    12/12/2017, 2:34 PM
    I also observe that the go-to example of why dependent types are useful is always Vector<N>, but usually I don't want to specify exactly how many elements a list has in the type, but being able to express non-emptyness (wish English had a short word for this) would have been concretely useful.
    👍 1
    p
    • 2
    • 1
  • k

    karelpeeters

    12/12/2017, 2:38 PM
    Are there any operations that works on eg. a non-empty list that don't work on an empty one? I can only think of
    list[0]
    .
    n
    • 2
    • 1
  • k

    karelpeeters

    12/12/2017, 2:39 PM
    Iteration works as expected if you respect the contracts of
    Iterator
    .
    v
    m
    +2
    • 5
    • 17
Powered by Linen
Title
k

karelpeeters

12/12/2017, 2:39 PM
Iteration works as expected if you respect the contracts of
Iterator
.
v

voddan

12/12/2017, 2:47 PM
I think @mikehearn means that side-effects of a loop were not run when lopped over an empty colection
k

karelpeeters

12/12/2017, 2:49 PM
I'm still having trouble imagining a useful scenario where this is a problem. Something like
var a = 3
for (c in emptyList()) a = 5
println(a)
maybe?
I'd be interested in seeing an example.
m

mikehearn

12/12/2017, 2:50 PM
The actual cases where this came up are more complex than small code snippets. Think: a plugin loading mechanism is supposed to register classes of a particular type, and there is meant to be at least one in a real deployment, but if it doesn't happen then the feature the plugin provides just silently vanishes.
you really want an ability to say, "give me a list of plugins and oh by the way, *there is supposed to always be at least one*" in the type signature.
and have the compiler generate the right assertions
Now, some smart alec is going to come along and say, but you can't do that without immutable lists because a thread could change it concurrently.... but I don't really care about that. Iterating over a list that another thread is changing is broken already. So it's OK if the compiler assumes the list won't change between check(isNotEmpty()) and usage.
k

karelpeeters

12/12/2017, 2:53 PM
For
varargs
I've done things like
fun max(first: Int, varargs rest: Int) = ...
, not sure if that's possible in your use case.
m

mikehearn

12/12/2017, 2:53 PM
yes that works for varargs. but not for general collections.
✔️ 1
c

cedric

12/12/2017, 9:51 PM
@mikehearn Just to clarify: you already have implemented such lists and wondering if it could be added to the stdlib?
m

mikehearn

12/13/2017, 9:49 AM
Yes I have them, but I'd rather it be in the type system more natively so as to avoid wrapper types
(with value types it may not matter at all)
p

pdvrieze

12/13/2017, 1:35 PM
@mikehearn Value types cannot really do it. You want typestate as: https://www.cs.cmu.edu/~aldrich/papers/onward2009-state.pdf
Although in the pattern of http://pcwalton.github.io/blog/2012/12/26/typestate-is-dead/ it may be able to use a generic parameter with state enums for a subset of it (an enumerable amount of states, not something like the actual amount of elements in a list).
m

mikehearn

12/13/2017, 3:04 PM
Well, you can pull it off today with wrapper classes and some extension functions. It's just kind of ugly and inefficient.
i've tried to implement type state in the kotlin compiler actually 🙂 well, i say "implement" ... i abused the internal contracts feature and commented out an error check that was getting in my way, before getting stuck because of course flow typing does not expect types to change exactly, only be narrowed. but it was a fun experiment.
but yes, you can use that approach if you don't care about the safety check poking out into the code.
View count: 1