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
dsl
  • m

    Marc Reichelt

    01/03/2018, 4:40 PM
    We recently wrote a backend with Kotlin + Jooby. To have good documentation we used swagger.io - but we had to write our
    swagger.yaml
    file ourselves. Using https://editor.swagger.io/ eased the pain, especially since it provides validation errors and code completion. Now I wonder whether I could write a Kotlin DSL for OpenAPI, and generate the
    swagger.yaml
    on the fly. So the initial results look tempting, as I can write:
    openapi {
        openapi { "3.0.1" }
        info {
            title { "Swagger Petstore" }
            version { "1.0.0" }
        }
    }
    But there are two things I dislike with this solution. One: I have to write a lot of code to get this basic functionality. And two: Nobody prevents me from calling
    info
    or
    title
    multiple times, or even omitting them totally. For example, this would be invalid:
    openapi {
        info {
            title { "Swagger Petstore" }
            title { "Swagger Petstore 2" }
            version { "1.0.0" }
        }
    }
    In contrast, writing the OpenAPI spec with data classes gains me more functionality than writing a custom DSL:
    Document(
            openapi = "3.0.1",
            info = Info(
                    title = "Swagger Petstore",
                    version = "1.0.0"
            )
    )
    Here I have to add
    openapi
    and
    info
    because they are both required, and IntelliJ tells me if there is a duplication error. So my question is: What do I gain from writing a DSL in this case, or is the OpenAPI spec not a good use case for it?
    • 1
    • 1
  • h

    helpermethod

    01/04/2018, 5:11 PM
    Hi, another question: Is it somehow possible to require that a method is called, something like
    foo {
        bar("bar") // this is required
        baz() // this is optional
    }
    o
    • 2
    • 1
  • k

    kristofdho

    01/23/2018, 11:45 AM
    this does allow you to change the order of the
    doThis
    etc calls, not sure if that's a problem
    c
    • 2
    • 1
  • k

    kikitux

    02/22/2018, 4:14 PM
    Hello, My name is Alvaro, native spanish speaker, sorry if my english is not very good. I am trying to learn a bit on how Kotlin for DSL fits, however the DSL concept in itself is new to me, so if anyone can point me to any resource that can help me to understand what a DSL is, so i can understand the benefits will help me to move into the next step that is produce a DSL in kotlin
    c
    • 2
    • 3
  • s

    snowe

    06/16/2018, 4:42 PM
    Yeah I had considered the unaryPlus operator, but then I'd have to define it on
    Any
    and that definitely isn't a good idea. Wait, unless, can I define
    unaryPlus
    just in the context of a block?
    c
    • 2
    • 2
  • d

    Dominaezzz

    11/13/2018, 10:29 AM
    Extension vs member methods for DSLs?
    w
    • 2
    • 1
  • t

    tjb

    11/20/2018, 4:44 AM
    haha sorry different question: is it difficult to use a DSL written in kotlin in a java project?
    h
    • 2
    • 2
  • t

    tjb

    11/26/2018, 3:03 AM
    fun match(block: MatchBuilder.() -> Unit = {}) {
            val matchBuilder = MatchBuilder()
            matchBuilder.block()
            match = match.plus(matchBuilder.build())
        }
    d
    • 2
    • 20
  • t

    tjb

    11/26/2018, 3:10 AM
    match {
                optional = false
            }
    
            with {
                "hello, world"
            }
    d
    • 2
    • 3
  • m

    Marc Knaup

    01/08/2019, 11:04 AM
    Hey guys, is there a way to disable parameter name hints using an annotation so that I can write a DSL which doesn’t show any of these hint?
    🙁 1
    🇳🇴 2
    c
    a
    • 3
    • 5
  • d

    digitalsanctum

    01/14/2019, 8:06 PM
    Does anyone have an example project to share that has good constructs for Java (builders for Java, data classes for Kotlin). I'm wondering if the pattern is to just create builders in addition to data class constructors using named params, default values, etc.
    s
    • 2
    • 4
  • m

    Marc Reichelt

    01/28/2019, 12:44 PM
    Mainly, the
    Configuration
    class does not have an
    isDirectory
    property - but how could the Groovy code then work in the first place?
    d
    • 2
    • 6
  • g

    GarouDan

    01/29/2019, 1:10 AM
    If we have something like
    group "com.company.team.project"
    version "0.0.1"
    in our
    build.gradle
    how can we convert this to a
    build.gradle.kts
    file? I tried something like:
    group("com.company.team.project")
    version("0.0.1")
    but it didn’t work.
    s
    • 2
    • 6
  • r

    ribesg

    01/29/2019, 10:07 AM
    Anyone else has intense freezes and lags when editing Gradle Kotlin DSL files?
    ➕ 1
    c
    d
    • 3
    • 4
  • s

    snowe

    01/31/2019, 6:05 PM
    what is the kotlin dsl equivalent of
    api()
    ? I thought it might be
    apiElements
    but then the module that uses
    apiElements
    fails to find the symbols in that jar.
    h
    • 2
    • 2
  • g

    GarouDan

    02/09/2019, 8:47 PM
    It looks like this call
    System.getProperty("configuration.build.dir")
    is not right. It is returning null but I could verify that a non empty value is passed in xcode.
    m
    • 2
    • 2
  • g

    GarouDan

    02/11/2019, 11:09 PM
    Guys, I’m trying to translate this excerpt
    jsJar.dependsOn(populateWebFolder)
    from a
    build.gradle
    file to a
    build.gradle.kts
    . How can I do this? This is part of:
    def webFolder = new File(project.buildDir, "../src/jsMain/web")
    def jsCompilations = kotlin.targets.js.compilations
    
    task populateWebFolder(dependsOn: [jsMainClasses]) {
        doLast {
            copy {
                from jsCompilations.main.output
                from kotlin.sourceSets.jsMain.resources.srcDirs
                jsCompilations.test.runtimeDependencyFiles.each {
                    if (it.exists() && !it.isDirectory()) {
                        from zipTree(it.absolutePath).matching { include '*.js' }
                    }
                }
                into webFolder
            }
        }
    }
    
    jsJar.dependsOn(populateWebFolder)
    
    task run(type: JavaExec, dependsOn: [jvmMainClasses, jsJar]) {
        main = "sample.SampleJvmKt"
        classpath { [
                kotlin.targets.jvm.compilations.main.output.allOutputs.files,
                configurations.jvmRuntimeClasspath,
        ] }
        args = []
    }
    h
    • 2
    • 2
  • g

    GarouDan

    02/25/2019, 6:29 PM
    Hi, does someone know how can I translate this task to
    build.gradle.kts
    ?
    compileTestKotlin2Js {
        kotlinOptions.metaInfo = true
        kotlinOptions.outputFile = "$project.buildDir.path/js-tests/${project.name}-tests.js"
        kotlinOptions.sourceMap = true
        kotlinOptions.moduleKind = 'commonjs'
    //    kotlinOptions.moduleName = project.name + "-test"
        kotlinOptions.main = "call"
    }
    This one here I could do something like:
    compileKotlin2Js {
        kotlinOptions.metaInfo = true
        kotlinOptions.outputFile = "$project.buildDir.path/js/${project.name}.js"
        kotlinOptions.sourceMap = true
        kotlinOptions.moduleKind = 'commonjs'
        kotlinOptions.main = "call"
    }
    tasks.withType<Kotlin2JsCompile> {
    	kotlinOptions {
    		//		languageVersion = "1.3"
    		metaInfo = true
    		outputFile = "${project.buildDir.path}/js/${project.name}.js"
    		sourceMap = true
    		sourceMapEmbedSources = "always"
    		moduleKind = "commonjs" // umd
    		main = "call"
    	}
    }
    c
    • 2
    • 6
  • m

    Marc Knaup

    02/25/2019, 8:03 PM
    Is this repo still relevant? https://github.com/gradle/kotlin-dsl Latest release there: 1.1.3 Latest release in Gradle Plugin Repo: 1.2.2 #confusing
    c
    • 2
    • 4
  • k

    Kirill Grouchnikov

    03/28/2019, 6:13 PM
    How would I even know that I can type + something
    s
    w
    h
    • 4
    • 6
  • m

    mgrzechocinski

    04/12/2019, 7:11 AM
    Hi. Would it be recorded?
    j
    • 2
    • 2
  • m

    Marc Reichelt

    05/01/2019, 12:21 PM
    Does anyone know what’s a good way to migrate Groovy Gradle Logic to Gradle Kotlin DSL? For example, I’m a little stuck on this one - even with code completion from Kotlin DSL (which is awesome!) I don’t know how I would migrate this: https://github.com/grpc/grpc-java/blob/master/examples/example-kotlin/build.gradle#L43-L51
    g
    c
    • 3
    • 10
  • m

    Marc Knaup

    05/08/2019, 10:04 PM
    Maybe both channels should be renamed to prevent the confusion 😄
    ➕ 1
    c
    • 2
    • 1
  • m

    Marc Knaup

    05/09/2019, 3:28 PM
    There's also confusion about the #gradle channel, so I would rename that too or open it to all Gradle+Kotlin-related questions 🙂
    s
    • 2
    • 1
  • s

    Slackbot

    05/22/2019, 6:05 AM
    This message was deleted.
    n
    c
    • 3
    • 3
  • m

    mingkangpan

    05/26/2019, 2:52 PM
    @SqlMarker
    object SQLBuilder {
        fun query(init: SqlSelectBuilder.() -> Unit): SqlSelectBuilder {
            val builder = SqlSelectBuilder()
            builder.init()
            return builder
        }
    }
    d
    h
    • 3
    • 3
  • j

    jw

    08/12/2019, 6:02 PM
    I have a DSL function whose lambda returns
    Any?
    allowing any object to be returned. This lambda's receiver is also a DSL type meaning there are functions you can call inside of it. The problem is that these functions return
    Unit
    thus completing the contract of the enclosing lambda and avoiding the need to actually return an object. Is there any way to avoid this?
    @MyDsl interface Foo {
      fun bar(lambda: Bar.() -> Any?)
    }
    @MyDsl interface Bar {
      fun someHelper(size: Int)
      fun otherHelper(flag: Boolean)
    }
    
    bar {
      someHelper(2)
      otherHelper(true)
      // should be required to return an object here
    }
    I tried to get clever with an overload of
    bar
    whose lambda returned
    Unit
    and was marked as an error, but you can't
    @JvmName
    an interface function. converting it to a class results in the
    Unit
    -returned lambda always being preferred. There's a Kotlin-internal annotation to lower its overload precedence, but I don't have access to that.
    s
    • 2
    • 2
  • s

    Shawn

    09/05/2019, 5:58 PM
    super newb question - does anyone have a blog post or two that collects like DSL best practices? I recently tried my hand at making a simple config-like language for a toy link shortener and am not sure if I put certain things in the right place
    s
    m
    • 3
    • 5
  • b

    benfleis

    09/18/2019, 7:16 AM
    Hey all, I have used Kotlin a bit here and there, but never really stuck my nose into the DSL opportunities. I have an existing, small custom DSL (perhaps close to a simplified haskell), whose main purpose is to provide a tiny, restrictive language (~40 functions). Is it possible either syntactically, or at compile time, to place heavy restrictions on the allowable functionality within a kotlin DSL? Thus for example, could I prevent basic string manipulation, except through my own pre-defined string manipulation functions? (I suspect this is partially in contrast to typical kotlin/DSL goals, but lack the experience.) Any tips/pointers to related work greatly appreciated. My googling so far has not led to any results.
    g
    e
    • 3
    • 24
  • m

    Marc Knaup

    10/04/2019, 7:26 AM
    TIL:
    someFuncReturningBool() && otherFuncReturningBool()
    and
    someFuncReturningBool() and otherFuncReturningBool()
    is not the same. The former short-circuits, the latter doesn’t. That hit me unexpectedly when I thought “oh that’s nice, I can just use
    and
    instead of
    &&
    in my DSL to make it more human-readable”.
    rule {
       condition {
          terms.assignmentAddress.isProvided() and
             terms.assignmentAddress.country.isNotSupported() // exception because access not allowed if isProvided() returns false
       }
    
       issue {
          "Terms: The address of the assignment is located in a country that is not supported."
       }
    }
    I presume there are only two ways to fix this. a) Use
    &&
    instead of
    and
    😥 b) Make all the functions which can be used in
    condition {}
    that currently return
    Boolean
    return something like
    Condition
    instead. That in turn would have an
    and
    infix operator which makes two
    Condition
    instances form a new
    Condition
    and thus allows for chaining with
    and
    . That would basically build a tree of
    Condition
    . I guess there are no alternatives for supporting
    and
    here?
    e
    • 2
    • 2
Powered by Linen
Title
m

Marc Knaup

10/04/2019, 7:26 AM
TIL:
someFuncReturningBool() && otherFuncReturningBool()
and
someFuncReturningBool() and otherFuncReturningBool()
is not the same. The former short-circuits, the latter doesn’t. That hit me unexpectedly when I thought “oh that’s nice, I can just use
and
instead of
&&
in my DSL to make it more human-readable”.
rule {
   condition {
      terms.assignmentAddress.isProvided() and
         terms.assignmentAddress.country.isNotSupported() // exception because access not allowed if isProvided() returns false
   }

   issue {
      "Terms: The address of the assignment is located in a country that is not supported."
   }
}
I presume there are only two ways to fix this. a) Use
&&
instead of
and
😥 b) Make all the functions which can be used in
condition {}
that currently return
Boolean
return something like
Condition
instead. That in turn would have an
and
infix operator which makes two
Condition
instances form a new
Condition
and thus allows for chaining with
and
. That would basically build a tree of
Condition
. I guess there are no alternatives for supporting
and
here?
e

efemoney

10/08/2019, 12:46 AM
You have to be careful,
and
is a bitwise operator not a boolean operator.
m

Marc Knaup

10/08/2019, 3:29 AM
I know. Yet it's defined on
Boolean
, hence the confusion :)
View count: 4