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

    Dominick

    04/23/2021, 1:57 AM
    I am trying to call Comparator.comparingLong with kotlin lambda syntax and I get the error: Calls to static methods in Java interfaces are prohibited in JVM target 1.6. Recompile with '-jvm-target 1.8' maven kotlin My IntelliJ Project Structure says to compile for platform JVM 1.8, my Settings in IntelliJ say for the Kotlin Compiler to use target 1.8, and maven has the following in the properties tag:
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    I don't understand why I get this error. If anyone has insight or a fix please share!
    e
    m
    • 3
    • 7
  • d

    dave08

    04/23/2021, 9:17 AM
    Just wondering, if there's sealed interfaces, what are the use cases for sealed classes now?
    h
    j
    c
    • 4
    • 6
  • s

    spand

    04/23/2021, 1:03 PM
    I am trying to set
    allWarningsAsErrors = true
    for all my modules regardless of them being, common, multiplatform-js, multiplatform-jvm, kotlinjs, kotlin ect. Is this the right type to search for ?
    subprojects {
        tasks.withType(org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.class) {
            kotlinOptions {
                allWarningsAsErrors = true
            }
        }
    }
    e
    • 2
    • 1
  • s

    Slackbot

    04/23/2021, 5:11 PM
    This message was deleted.
    c
    i
    e
    • 4
    • 3
  • d

    Dominaezzz

    04/24/2021, 9:19 AM
    Is this supposed to not work? (I'm using JVM IR)
    val myNum: Int = 5
    val myBigNum: Long = myNum // fine
    val myMaybeBigNum: Long? = myNum // not fine
    c
    a
    • 3
    • 4
  • f

    F0X

    04/24/2021, 9:37 AM
    Whats the best way to write unsigned integer literals for signed types? For example I'd like to write
    0xFF
    and have that be converted to a signed
    Byte
    d
    f
    t
    • 4
    • 6
  • y

    Yaniv Sosnovsky

    04/24/2021, 3:11 PM
    Hi can anyone help we with kotlin deserialization? I’m using retrofit with kotlinx serialization and I have a case where I can get 2 types of responses from the server: the first case returns a list of results with “drinks” key,
    {"drinks":[{"strDrink":"Jelly Bean","strDrinkThumb":"https:\/\/<http://www.thecocktaildb.com|www.thecocktaildb.com>\/images\/media\/drink\/bglc6y1504388797.jpg","idDrink":"13775"},{"strDrink":"Turf Cocktail","strDrinkThumb":"https:\/\/<http://www.thecocktaildb.com|www.thecocktaildb.com>\/images\/media\/drink\/utypqq1441554367.jpg","idDrink":"12418"}]}
    but sometimes the server returns the following:
    "{"drinks":"None Found"}"
    Before using kotlinx I had a custom type convertor with Gson, and that worked fine, but I’m struggling with kotlin. I tried to create a KSerializer to try to parse the result, and return an object with an empty list if an exception is thrown, but I keep getting this exception:
    java.lang.IllegalStateException: Reader has not consumed the whole input: JsonReader(source='{"drinks":"None Found"}', currentPosition=22, tokenClass=1, tokenPosition=10, offset=11)
    Any ideas how to solve this? I can always return a string instead of a data class, but this is ugly AF
    e
    • 2
    • 2
  • m

    Michael

    04/26/2021, 7:29 AM
    https://github.com/JetBrains/kotlin/releases/tag/build-1.5.20-dev-5730
    j
    l
    • 3
    • 8
  • u

    user

    04/26/2021, 8:40 AM
    message has been deleted
    👍 4
    👍🏼 2
    z
    • 1
    • 1
  • s

    Stephan Schroeder

    04/26/2021, 11:27 AM
    has someone a good tip for a kapt tutorial for serverside annotation processing? (Android is not involved in any way. The task is to generate a documentation file containing which classes contain certain annotations. Since it's Kotlin files we're talking about, I guess that kapt is the right tool for the job!?)
    b
    e
    w
    • 4
    • 12
  • a

    algo112

    04/26/2021, 1:40 PM
    Can write it better ??🙂
    val listType = object : TypeToken<List<Cookie>>() {}.type
    val encodedCookie = sharedPreferences.getString(url.host, null)
    val cookies: List<Cookie>? = encodedCookie?.run { gson.fromJson(encodedCookie, listType) }
    return cookies ?: ArrayList()
    d
    s
    j
    • 4
    • 8
  • s

    stanislav.erokhin

    04/26/2021, 3:06 PM
    Yea, we are starting the 1.5.0 release activities. Please be patient, it will take a bit of time. It will be officially out only after the blog post appears in blog.jetbrains.com/kotlin. 🙂
    🎉 26
    :kotlin-intensifies: 22
    c
    l
    +2
    • 5
    • 9
  • u

    ursus

    04/26/2021, 5:19 PM
    Why is this not a compile time error? Was this always like this? I'd expect this to be a regular type mismatch compile error
    l
    • 2
    • 2
  • d

    David Smith

    04/26/2021, 8:52 PM
    is there a channel I can post a job offer?
    u
    • 2
    • 2
  • b

    Big Chungus

    04/26/2021, 10:11 PM
    I've stumbled upon an old kotlin channel on gitter recently and couldn't help but wonder why you've moved away from it to slack? Gitter messages seem to be google'able in addition to being open for all. Just curious is all. Would help a ton in persisting valuable information exchanged here.
    n
    b
    o
    • 4
    • 42
  • u

    ursus

    04/26/2021, 11:24 PM
    What on earth am I doing wrong? Is this not how you use
    @OptIn
    ?
    z
    • 2
    • 14
  • u

    ursus

    04/27/2021, 2:19 AM
    Anybody gettting this after migrating to 1.5.0?
    e: org.jetbrains.kotlin.backend.common.BackendException: Backend Internal error: Exception during psi2ir
    File being compiled: C:/Users/ursus/AndroidStudioProjects/o2-selfcare-android/complex-syncer/contract/src/main/java/sk/o2/complex/Mappers.kt
    The root cause java.lang.NullPointerException was thrown at: org.jetbrains.kotlin.psi2ir.generators.BodyGenerator.generateSuperConstructorCall(BodyGenerator.kt:242)
    	at org.jetbrains.kotlin.backend.common.CodegenUtil.reportBackendException(CodegenUtil.kt:239)
    	at org.jetbrains.kotlin.backend.common.CodegenUtil.reportBackendException$default(CodegenUtil.kt:235)
    	at org.jetbrains.kotlin.psi2ir.generators.DeclarationGenerator.generateMemberDeclaration(DeclarationGenerator.kt:78)
    	at org.jetbrains.kotlin.psi2ir.generators.ModuleGenerator.generateSingleFile(ModuleGenerator.kt:83)
    	at org.jetbrains.kotlin.psi2ir.generators.ModuleGenerator.generateModuleFragment(ModuleGenerator.kt:50)
    	at org.jetbrains.kotlin.psi2ir.Psi2IrTranslator.generateModuleFragment(Psi2IrTranslator.kt:81)
    	at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.convertToIr(JvmIrCodegenFactory.kt:140)
    	at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.convertToIr$default(JvmIrCodegenFactory.kt:66)
    	at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.generateModule(JvmIrCodegenFactory.kt:61)
    	at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.compileCorrectFiles(KotlinCodegenFacade.java:35)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.generate(KotlinToJVMBytecodeCompiler.kt:592)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:212)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli$default(KotlinToJVMBytecodeCompiler.kt:155)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:169)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:52)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:88)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:44)
    	at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:98)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:386)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:110)
    a
    • 2
    • 6
  • m

    Muhammad Zaryab Rafique

    04/27/2021, 4:28 AM
    Hi Devs, kindly guide me, how to decrease the size of apk file ?
    :not-kotlin: 9
    :stackoverflow: 1
    u
    c
    • 3
    • 5
  • m

    Michael Böiers

    04/27/2021, 5:58 AM
    While converting legacy Java code to Kotlin, I encountered this unpleasant effect: https://pl.kotl.in/-aERlNLZ0
    data class A(var b: B? = null)
    data class B(var a: A? = null)
    
    fun main() {
       val a = A()
       val b = B(a).also { a.b = it }
       println(a) // produces StackOverflow as the two toString impls call each other indefinitely
    }
    I suppose this is unavoidable - nevertheless, it can kill an application merely by converting a plain Java class into a data class. Any thoughts?
    e
    j
    +2
    • 5
    • 15
  • p

    PHondogo

    04/27/2021, 9:47 AM
    I like how data class auto generate copy function with optional parameters to change any field on copy. It will be very good if such possibility will appear in non data classes, for example annotated with some annotation.
    e
    r
    t
    • 4
    • 23
  • t

    thanksforallthefish

    04/27/2021, 12:40 PM
    wait, what? https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-bom/1.5.0/pom kotlin 1.5 was sneaky released yesterday or did I just miss the announcements? also no tag https://github.com/JetBrains/kotlin yet 🤔
    d
    z
    +3
    • 6
    • 10
  • k

    Karlo Lozovina

    04/27/2021, 3:19 PM
    Is there a way to prohibit changing
    latinit
    properties after they've been initialized? Something in the stdlib maybe?
    e
    n
    • 3
    • 6
  • q

    Quincy

    04/27/2021, 7:34 PM
    In Java, I can create a map using the toMap collector, like this:
    Stream.of(...)
        .toMap(
            keySelector,
            valueTransform,
            (x, y) -> {
                if (x.getTimestamp().isBefore(y.getTimestamp())) return x;
                else return y;
            });
    If there would be duplicate values then the third argument determines what to do about it. In Kotlin, the
    associateBy
    function always keeps the most recent value. Is there a way to create a map the way Java does, where I get to decide what to do with duplicates?
    n
    r
    • 3
    • 10
  • k

    Karlo Lozovina

    04/27/2021, 7:46 PM
    ie, is it possible in the super class init block get access to values that the child class has overriden?
    h
    • 2
    • 3
  • b

    blakelee

    04/27/2021, 10:08 PM
    I don't think this is possible, but I figured I would ask anyway. Is it possible to chain together multiple enum class into a builder pattern sort of deal For instance I have something like this
    enum class Page {
        PAGE_1,
        PAGE_2;
    }
    
    enum class Page1Section {
        SECTION_A,
        SECTION_B
    }
    
    enum class Page2Section {
        SECTION_1,
        SECTION_2
    }
    With my end goal being something like
    Page.PAGE_1.SECTION_A.build()
    and if I selected PAGE_2 then
    Page.PAGE_2.SECTION_1.build()
    Maybe this would be better in sealed classes If I selected PAGE_1, if I were to type
    .
    then I would get the list of Page1Section's then if I click
    .
    again perhaps another list of items
    n
    m
    • 3
    • 5
  • c

    Chuck Canning

    04/27/2021, 11:13 PM
    if you are running the latest 1.5 kotlin RC, is there a need to specify stdlib-jdk8 vs stdlib?
    s
    e
    s
    • 4
    • 4
  • d

    David Smith

    04/28/2021, 12:42 AM
    I’m playing around with a vdom and for this I need fast access to a hash of each node, since I’m using data classes I have access to
    hashCode()
    already but I want to avoid having to call it as a function because during a diff of a deeply nested structure this could happen many many times, i.e. I want to memoize the call. Can I simply add a property that is initialized to
    this.hashCode()
    ? I’ve implemented the following which seems to work (although I haven’t tested it properly yet)
    sealed class Node {
        data class TextNode(val value: String) : Node() {
            override val hash = this.hashCode()
        }
        data class TagNode(val name: String, val attributes: List<Attribute>, val children: List<Node>) : Node() {
            override val hash = this.hashCode()
        }
        abstract val hash: Int
    }
    e
    • 2
    • 5
  • a

    amr s

    04/28/2021, 2:39 AM
    Has anyone built any apps with JetBrains compose yet? If so pls share GitHub. Also, what ui framework does JetBrains compose use, I heard that it does not have all the same functionality as jet pack compose but is not far off
    a
    • 2
    • 1
  • c

    CLOVIS

    04/28/2021, 7:47 AM
    I was not expecting
    tailrec suspend
    to work, but it does! Thanks to the team, that must have been a weird edge case to handle.
    e
    • 2
    • 1
  • j

    jim

    04/28/2021, 6:14 PM
    Hey everybody, Thanks for having me. Can somebody tell me how to resolve this ambiguity without
    it.
    ?
    kotlin
            val a = "1 2\n3 4".lines().map{CharSequence::split("\\s+".toRegex())}
    log
    Matrix.kt: (10, 59): This syntax is reserved for future use; to call a reference, enclose it in parentheses: (foo::bar)(args)
    e: /home/a/github/exercism/kotlin/matrix/src/main/kotlin/Matrix.kt: (10, 54): Overload resolution ambiguity:
    public fun CharSequence.split(regex: Pattern, limit: Int = ...): List<String> defined in kotlin.text
    public fun CharSequence.split(vararg delimiters: String, ignoreCase: Boolean = ..., limit: Int = ...): List<String> defined in kotlin.text
    public fun CharSequence.split(vararg delimiters: Char, ignoreCase: Boolean = ..., limit: Int = ...): List<String> defined in kotlin.text
    @InlineOnly public inline fun CharSequence.split(regex: Regex, limit: Int = ...): List<String> defined in kotlin.text
    n
    q
    +3
    • 6
    • 27
Powered by Linen
Title
j

jim

04/28/2021, 6:14 PM
Hey everybody, Thanks for having me. Can somebody tell me how to resolve this ambiguity without
it.
?
kotlin
        val a = "1 2\n3 4".lines().map{CharSequence::split("\\s+".toRegex())}
log
Matrix.kt: (10, 59): This syntax is reserved for future use; to call a reference, enclose it in parentheses: (foo::bar)(args)
e: /home/a/github/exercism/kotlin/matrix/src/main/kotlin/Matrix.kt: (10, 54): Overload resolution ambiguity:
public fun CharSequence.split(regex: Pattern, limit: Int = ...): List<String> defined in kotlin.text
public fun CharSequence.split(vararg delimiters: String, ignoreCase: Boolean = ..., limit: Int = ...): List<String> defined in kotlin.text
public fun CharSequence.split(vararg delimiters: Char, ignoreCase: Boolean = ..., limit: Int = ...): List<String> defined in kotlin.text
@InlineOnly public inline fun CharSequence.split(regex: Regex, limit: Int = ...): List<String> defined in kotlin.text
n

nanodeath

04/28/2021, 6:15 PM
is it a method reference or a method call? you can't do both
j

jim

04/28/2021, 6:21 PM
well, I have tried different things
val a = "1 2\n3 4".lines().map(CharSequence::split("\\s+".toRegex()))
isn't working either.
And I saw
fun scoreWord(word: String): Int {
        if(word.isEmpty()) return 0

        return word
            .map(Character::toUpperCase)
            .map { scores.getOrDefault(it, 0) }
            .reduce(Int::plus)
    }
n

nanodeath

04/28/2021, 6:26 PM
I mean `Class::method(`is never going to work
j

jim

04/28/2021, 6:28 PM
Sorry, I am new to this. isn't
Character::toUpperCase
Class::method
?
n

nanodeath

04/28/2021, 6:29 PM
yes, but there's no attempted method invocation there -- that
(
I added isn't a typo
btw
.map(Character::toUpperCase)
is exactly equivalent to
.map { it.toUpperCase() }
or, more verbosely,
.map { c: Character -> c.toUpperCase() }
I don't think there's any way around doing this:
val spaces = "\\s+".toRegex()
val a = "blah".lines().map { it.split(spaces) }
j

jim

04/28/2021, 6:32 PM
right, right, I was looking to the equivalent thing to
map{it.split("\\s+".toRegex())}
.
And you are saying it doesn't work because split takes 1 parameter, right?
n

nanodeath

04/28/2021, 6:37 PM
if split returned a
(Character -> T)
instead of a String, you could probably say
map(it.split("\s"))
but yeah,
split
accepts one parameter, and that parameter isn't the string being split; it's the pattern you want to split on, which is crucial
q

Quincy

04/28/2021, 6:57 PM
You could maybe do something like this?
val spaces = "\\s+".toRegex()
val spliter = { s: String -> s.split(spaces) }
val a = "blah".lines().map(splitter)
But if the actual use case is not more complicated than what you've shown it's not really buying you anything.
j

jim

04/28/2021, 6:59 PM
ok, I don't think I understand if
.map(Character::toUpperCase)
gets translated to
.map { c: Character -> c.toUpperCase() }
, why
.map(CharSequence::split("\\s+".toRegex())
is not translated to
.map{cs:CharSequence -> cs.split("\\s+".toRegex())}
. I just mark it as one parameter extra. Does not work. Thank you for the replies.
n

nanodeath

04/28/2021, 6:59 PM
it's just invalid syntax. you can't combine a method reference with a method invocation.
@Quincy yeah, that would work. might also promote the
splitter
thing into an actual method; that might be more efficient
q

Quincy

04/28/2021, 7:02 PM
@Ol' Dawg a reference like
Character::toUppercase
is a way of referring to a specific function defined elsewhere which satisfies the type
(Character) -> Character
r

Roukanken

04/28/2021, 7:22 PM
Disclaimer: please really don't do this, I'm just messing with stuff https://pl.kotl.in/IF5TTwTJm this actually works the obvious question is why do
mySplit
? ... well original split has like 4 overloads and compiler complains it can't chose. Afaik, doing this is stretching the limits of Kotlin's type system anyways, to real question: Map can only handle if you pass it reference to function taking 1 argument - because it has 1 value (the
it
) and can just chunk it there. But split needs at least 2 arguments -
a.split(b)
both
a
and
b
are arguments, and
map
only has 1 value. And no, you can't just pass 1 argument to reference and expect a new function to be created (sadly)
n

Nir

04/28/2021, 7:30 PM
I'm not really sure what partial buys you here
r

Roukanken

04/28/2021, 7:31 PM
nothing 😛 Just wanted to try if that would work even I'm all for just specifying it - you won't get clearer than that if he hates to use
it
then easy solution: name it
n

Nir

04/28/2021, 7:31 PM
"blah".lines().map { it.split("\\s+".toRegex()) }
Already works and is perfectly readable, the problem is that you'd be executing the toRegex over and over
Which is a problem shared by the solution you posted
The ugliest part of the kotlin solution is that you have to create this
spaces
variable but it's not clear how you'd hope to avoid that in general.
r

Roukanken

04/28/2021, 7:42 PM
the
partial
solution mess wouldn't actually call
toRegex
over and over - it passes the function just once to map, with already "inlined" argument but without managing to resolve that overload ambiguity, it's not really viable solution
n

Nir

04/28/2021, 8:02 PM
Ah you're totally right, my bad
Probably not recommended either but a way to make it work as a one liner, without any extra machinery:
val a = "1 2\n3 4"
        .lines()
        .map("\\s+".toRegex().let{ {line -> line.split(it)} })
w

wbertan

04/28/2021, 9:43 PM
It seems
Regex
already has a
split
. Can check if the output is desirable, but could try this:
val a = "1 2\n3 4".lines().map("\\s+".toRegex()::split)
The docs says:
Splits the input CharSequence around matches of this regular expression.
So I believe it should work as expected.
➕ 2
View count: 6