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
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
j

janos

07/24/2018, 5:51 PM
I guess withContext has to be a function which get a lambda function as param, but the concrete implementation is not clear
l

Luke

07/24/2018, 5:53 PM
fun withContext(block: (Context) -> Unit){}
j

janos

07/24/2018, 5:54 PM
Yes, so far I got that too
l

Luke

07/24/2018, 5:54 PM
and you can call
block()
inside to execute
with the context argument of course
j

janos

07/24/2018, 5:56 PM
you mean call the block method?
l

Luke

07/24/2018, 5:57 PM
Well I assume you want to execute whatever is inside so yes,
block(context)
j

janos

07/24/2018, 5:58 PM
but where does the context comming from?
l

Luke

07/24/2018, 5:58 PM
don't you have a context instance variable?
do you want to pass a context to the method as well?
I think I don't quite understand what you are trying to do
j

janos

07/24/2018, 6:00 PM
so in my original code I've created a new Service with he `createServiceFoo`method based on the context
the ServiceFoo needs an enhanced baseClient
to enhance the baseClient I need the context
based on the context I can create a new baseClient which I can base to the ServiceFoo and use it there
just check my original code
l

Luke

07/24/2018, 6:01 PM
ah ok I see now
k

karelpeeters

07/24/2018, 6:01 PM
So you want both a context and a client available in the lambda?
Where you're able to implicitly call things on the context?
j

janos

07/24/2018, 6:03 PM
I need the context to be able to create an instance of ServoceFoo
l

Luke

07/24/2018, 6:04 PM
you'll have to save the context in ServiceFoo then
j

janos

07/24/2018, 6:04 PM
my Factory class has one public method which gets the context, adds it to his private baseClient (it creates a mutation of the baseClient) and the mutated baseClient can be used in my Service
the Service does not no anything about the context, he just gets a client as a constructor parameter and uses it
l

Luke

07/24/2018, 6:06 PM
but you need that context to call the block in withContext
k

karelpeeters

07/24/2018, 6:06 PM
Something like this:
class ServiceFooFactory {
	...
	fun createWithContext(context: Context, block: ServiceFoo.() -> Unit): ServiceFoo {
		val service = createServiceFoo(context)
		service.block()
		return service
	}
}
Called like
val service = factory.createWithContext(context) { hello("Bar") }
l

Luke

07/24/2018, 6:07 PM
do you have access to the context from baseClient?
j

janos

07/24/2018, 6:09 PM
@karelpeeters yes!!!
but in scala you can do sg like
factory.createWithContext {context -> hello("Bar") }
can't we have the context in the same closure?
l

Luke

07/24/2018, 6:11 PM
fun withContext(block: (Context) -> Unit){block(baseClient.context)}
?
j

janos

07/24/2018, 6:12 PM
ohh that was your quest
the context is comming from outside
and it has to be added to the baseClient
it actually looks like this:
fun someFun(callParam, context) {
    factory.createServiceFoo(context).hello(callParam)
}
based on @karelpeeters's idea I can do now this:
fun someFun(callParam, context) {
    factory.createWithContext(context) {
        hello(callParam)
    }
}
which is a nice step forward
and my end goal is this:
fun someFun(callParam, context) {
    factory.createWithContext { context ->
        hello(callParam)
    }
}
k

karelpeeters

07/24/2018, 6:18 PM
I don't really see how that's different from what I did, do you just want a different syntax for "passing
context
as a parameter"?
j

janos

07/24/2018, 6:18 PM
yes!
just for the sake of syntax sugar
technically your solution already does what it has to do
k

karelpeeters

07/24/2018, 6:21 PM
Isn't that really confusing?
j

janos

07/24/2018, 6:21 PM
do you think?
I think frameworks like Play are doing this all the time
Anyways thanks a lot!
for both of you
oh shit... 😞
the withContext cannot return with value of the hello() function
k

karelpeeters

07/24/2018, 6:49 PM
It should work, any value for the last line is okay for a Unit-returning function normally.
And I think it's confusing because you're conflating parameters with _ arguments_.
context
in
{ context -> ... }
is normally a parameter, but you want it it be a value, ie. an argument..
j

janos

07/24/2018, 6:51 PM
I have cheated a little bit and checked the Kotlin's with function
based on that this is what I did:
fun <R> with(context: Context, block: Api.() -> R): R {
        val service = Api(baseClinet.addHeader(context))
        return service.block()
    }
val retVal: String = serviceFoo.with(HttpContext) { hello("WithContext")  }
this is what I can do now 🙂
and the retVal's type will be always the return type of the method call inside the closure
k

karelpeeters

07/24/2018, 6:54 PM
Ah isn't it good enough to hardcode that it returns the service?
j

janos

07/24/2018, 6:56 PM
nope in the higher function I have to return with the service function's return object
k

karelpeeters

07/24/2018, 6:56 PM
I see.
j

janos

07/24/2018, 6:57 PM
So
This is what I've ended up with:
class ServiceFoo {
    private val baseClient = Client()
    

    internal fun <R> with(context: Context, block: Api.() -> R): R {
        val service = Api(baseClient.addHeader(context))
        return service.block()
    }

    internal class Api(private val enhancedClient: Client) {
        fun hello(name: String): String {
            enhancedClient.getMethod(name)
            return name
        }


        fun hello2(name: String): Int {
            enhancedClient.getMethod(name)
            return 2
        }
    }
}

fun main(args: Array<String>) {
    val serviceFoo = ServiceFoo()


    val retVal: Int = serviceFoo.with(HttpContext) {
        hello2("WithContext")
    }
}
What do you think? Do you like the naming or should I leave the wrapper class as
ServiceFooFactory
and the
Api
as
ServiceFoo
Check this:
internal fun <R> with(context: Context, block: Api.() -> R): R = Api(baseClient.addHeader(context)).run(block)
I've transformed it to a one liner! 🙂
@karelpeeters thanks a lot! I really like what we did here 🙂
k

karelpeeters

07/24/2018, 7:57 PM
Nice one liner! Glad I could be of some help even with my choppy internet.
Naming you'll have to decide for yourself as I don't have the full context (heh) here 😒imple_smile: