https://kotlinlang.org logo
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
benchmarks
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
confetti
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
hiring-french
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
lincheck
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
Title
o

Orhan Tozan

03/31/2022, 10:20 AM
I want to emit 6 times the same composable (Card), but in the middle, I want a Divider. So I want to get something like: C C C D C C C How would one do this?
f

Filip Wiesner

03/31/2022, 10:23 AM
repeat(3) { C() }
D()
repeat(3) { C() }

//or maybe

repeat(7) {
  if (it == 3) D() else C()
}
o

Orhan Tozan

03/31/2022, 10:25 AM
I have the first one already, but I think it could be cleaner so I don't have to duplicate the logic I'm writing in the two repeat blocks. I was thinking about doing something like: repeat(6) { C }.add(3, D)
But that obviously doesn't work in Compose
f

Filip Wiesner

03/31/2022, 10:27 AM
You can make something like that work. You have the full power of Kotlin, the possibilities are endless 😄
o

Orhan Tozan

03/31/2022, 10:29 AM
@Filip Wiesner I was thinking about that, but it's not that easy. I think the problem here is, that Compose doesn't return anything, but emits things. I think it would be easy to do something like this in a return-based system like ReactJS, but in Compose, every time you call a Composable, it runs. It's like a side effect
f

Filip Wiesner

03/31/2022, 10:30 AM
Couldn't you return a @Composable function? 🤔
o

Orhan Tozan

03/31/2022, 10:31 AM
Hmm gonna try
f

Filip Wiesner

03/31/2022, 10:32 AM
Something like movableContentOf()
o

Orhan Tozan

03/31/2022, 10:37 AM
buildList {
            repeat(6) { index ->
                add(
                    @Composable {
                        C(...)
                    }
                )
            }
        }
This gives me the following error: Internal Error occurred while analyzing this expression
@Composable { ... }
is the right way to create a Composable lambda right?
c

Csaba Szugyiczki

03/31/2022, 10:49 AM
Do not oversimplify things, they just get messy after a certain point
👍 1
I think there is nothing wrong with the 1st suggestion
but if you want you can have a
@Composable
fun CardGroup(count: Int) {
    repeat(count) { Card() }
}
and then write
CardGroup(count = 3)
Divider()
CardGroup(count = 3)
o

Orhan Tozan

03/31/2022, 10:53 AM
@Csaba Szugyiczki
Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = modifier.fillMaxWidth(),
    ) {

        repeat(3) { index ->

            Cell(
                value = value[index],
                onValueChange = { newNumber ->
                    val newValue = value.toMutableList().apply { set(index, newNumber) }
                    val newNumberWasEntered = value != newValue && newNumber != null

                    onValueChange(newValue)

                    if (newNumberWasEntered) {
                        focusManager.moveFocus(FocusDirection.Right)
                    }
                },
                imeAction = ImeAction.Next,
                onKeyboardAction = {
                    focusManager.moveFocus(FocusDirection.Right)
                },
                modifier = Modifier
                    .weight(1f)
                    .padding(end = 10.dp)
                    .onFocusChanged { focusState ->
                        if (focusState.isFocused) {
                            val newValue = value
                                .toMutableList()
                                .apply { set(index, null) }
                                .toList()
                            onValueChange(newValue)
                        }
                    },
            )
        }

        Divider(
            color = MaterialTheme.colors.primary,
            thickness = 2.dp,
            modifier = Modifier
                .width(10.dp)
        )

        repeat(3) { loopIndex ->

            val digitIndex = loopIndex + 3

            val isLastCell = digitIndex == value.lastIndex

            Cell(
                value = value[digitIndex],
                onValueChange = { newNumber ->
                    val newValue = value
                        .toMutableList()
                        .apply { set(digitIndex, newNumber) }
                        .toList()
                    val newNumberWasEntered = value != newValue && newNumber != null
                    onValueChange(newValue)
                    if (newNumberWasEntered) {
                        focusManager.moveFocus(FocusDirection.Right)
                    }
                },
                imeAction =
                if (isLastCell) {
                    ImeAction.Done
                } else {
                    ImeAction.Next
                },
                onKeyboardAction = {
                    if (isLastCell) {
                        focusManager.clearFocus()
                    } else {
                        focusManager.moveFocus(FocusDirection.Right)
                    }
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 10.dp)
                    .weight(1f)
                    .onFocusChanged { focusState ->
                        if (focusState.isFocused) {
                            val newValue = value
                                .toMutableList()
                                .apply { set(digitIndex, null) }
                                .toList()
                            onValueChange(newValue)
                        }
                    },
            )
        }
    }
c

Csaba Szugyiczki

03/31/2022, 10:53 AM
What you mean by composable lambda is I think referred to as Slot in Compose and looks like this:
content: @Composable () -> Unit
This concept is all over compose
o

Orhan Tozan

03/31/2022, 10:53 AM
Above is my real code
c

Csaba Szugyiczki

03/31/2022, 10:55 AM
Ohh, I think I know what you want to create. Is it a 6 digit input box? I think it is much easier to have only one invisible Input box, and just display the entered digits however you want
o

Orhan Tozan

03/31/2022, 10:57 AM
@Csaba Szugyiczki In react, you can do something like
const items = Array(6) { C() }
items.splice(3, 0, D())
// items is now C C C D C C C
How would you do this in Compose?
c

Csaba Szugyiczki

03/31/2022, 10:58 AM
That is not possible in Compose Im affraid
o

Orhan Tozan

03/31/2022, 10:58 AM
@Csaba Szugyiczki yes it is a 6 digit input box. Could you elaborate on the one invisible input box part?
@Csaba Szugyiczki that's unfortunate, and a bit dissappointing IMO. It reduces the power of Compose if that's the case in my eyes. I'm open to be proven wrong
c

Csaba Szugyiczki

03/31/2022, 10:59 AM
Basically you would have an input field covering your whole view. But make it transparent. And below it you could draw the 6 boxes in a Row, and have whatever decoration on the boxes, or between them. You just have to make sure the user knows which digit is typed at the moment
Composable functions return nothing. They are plain kotlin functions without a return value, so there is nothing that you could add to a list either
o

Orhan Tozan

03/31/2022, 11:01 AM
Not sure if it is easier to build something like this into one view
(Just the 6 boxes part)
Yes, they return nothing indeed. Which can be an advantage in some cases: like being able to write:
if (showButton) {
    Button()
}
instead of
if (showButton) {
    Button()
} else {
    null
}
but it also has it's flaws, as you now lose the power of the regular programming power of transforming and mapping values. Example is that we can't achieve my React example few messages above
It loses the purity of functional programming
f

Filip Wiesner

03/31/2022, 11:08 AM
The Composable functions are intended for "Data -> UI" transformation. You can still "transform and map" the data before you emit UI based on it.
o

Orhan Tozan

03/31/2022, 11:16 AM
Hmm I guess so, but that means I now have to create a new data model for each UI component, which is more work
a

Albert Chang

03/31/2022, 11:33 AM
Something like
val card = @Composable { Card() }
repeat(3) { card() }
D()
repeat(3) { card() }
will work.
☝️ 1
👍 1
o

Orhan Tozan

03/31/2022, 12:24 PM
Yep that's what I've sticked with