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

    Joel Pedraza

    07/10/2020, 12:46 AM
    Is there any way to invoke an
    inline
    function from kotlin code without inlining the body at the call site? (similar to how it would be called from java code invoking it from ex:
    FooKt.myInlinedFun()
    ). Please spare the the 20 questions for determining if this an XY problem, just a curiosity if such a calling convention exists :)
    d
    r
    • 3
    • 2
  • e

    E.Kisaragi

    07/10/2020, 3:10 AM
    where does naming of crossinline come?
    👍 2
    k
    • 2
    • 2
  • d

    dimsuz

    07/10/2020, 9:35 AM
    I have a simply looking composition with generics and have even the new type inference fail on it. Is this a bug?
    interface Validator<T> {
      fun validate(input: T)
      fun and(other: Validator<T>): Validator<T> = TODO()
    }
    
    fun <T> andExternal(v1: Validator<T>, v2: Validator<T>): Validator<T> = TODO()
    
    fun <T> isNotEmpty(): Validator<T> = TODO()
    fun <T> isNotBlank(): Validator<T> = TODO()
    
    fun doStuff(validator: Validator<String>) { }
    
    fun main() {
      // isNotEmpty is highlighted: "not enough information to infer type variable T"
      doStuff(isNotEmpty().and(isNotBlank()))
      // no error when using external variant of "and", inferred as String!
      doStuff(andExternal(isNotEmpty(), isNotBlank()))
    }
    f
    • 2
    • 4
  • b

    bbaldino

    07/10/2020, 5:12 PM
    Is it possible to get a
    Class<SomeEnumType>
    from a
    KType
    created elsewhere via
    typeOf<SomeEnumType>()
    ? I feel like it should be possible, but I'm struggling to find the right call to get it.
    z
    b
    d
    • 4
    • 27
  • k

    kagomez

    07/10/2020, 11:36 PM
    Hi, does anyone remember what the name for val (prop1, prop2) object is called?
    z
    s
    • 3
    • 5
  • r

    rahulsom

    07/10/2020, 11:57 PM
    I have a gradle/kotlin-jvm project with 76 files and 4255 total LOC. The compileKotlin task takes ~20 minutes. I would like to learn how to debug this. Is there any guide on extracting this information from the compiler?
    ✅ 1
    r
    j
    c
    • 4
    • 11
  • l

    LastExceed

    07/11/2020, 6:34 AM
    myMutableInt = myMutableInt + 2
    can be simplified to
    myMutableInt += 2
    but is there any way to do something similar with non-operator functions, e.g. simplifying
    myMutableInt = myMutableInt.coerceIn(10, 100)
    to something like
    myMutableInt .= coerceIn(10,100) //not valid syntax
    ?
    i
    a
    e
    • 4
    • 13
  • g

    Gilles Barbier

    07/11/2020, 9:29 AM
    hi all, given this function
    inline fun <reified T> proxy() = (something...) as T
    I can use use as
    val proxy = proxy<MyClass>()
    - but how can I use it from an interface to obtain a proxy of a class implementing this interface?
    z
    • 2
    • 2
  • p

    Philipp Mayer

    07/11/2020, 10:42 AM
    Hey guys, can I somehow execute the creation of
    MqttMessage
    as an operation right on the array?
    fun createMessage(message: String): MqttMessage {
        val array = message.map { it.toByte() }
                .toByteArray()
        return MqttMessage(array)
    }
    Something like:
    fun createMessage(message: String): MqttMessage = message.map { it.toByte() }
            .toByteArray()
            .map { MqttMessage(it) }
    But the last map would have to be on the whole array. Thanks!
    m
    • 2
    • 3
  • s

    Slackbot

    07/12/2020, 2:22 PM
    This message was deleted.
    i
    • 2
    • 1
  • h

    Hullaballoonatic

    07/12/2020, 6:56 PM
    why is
    Number
    so limited? why doesn't it look something like this, at the very least?
    interface Number<N: Number<N> : Comparable<N> {
        operator fun plus(other: N): N
        operator fun minus(other: N): N
        operator fun times(other: N): N
        operator fun div(other: N): N
        operator fun unaryMinus(): N
    
        val minValue: N
        val maxValue: N
    
        fun inverse(): N
    
        fun toDouble(): Double
        fun toFloat(): Float
        fun toLong(): Long
        fun toInt(): Int
        fun toChar(): Char
        fun toShort(): Short
        fun toByte(): Byte
    }
    am i wrong in thinking all subclasses of Number implement those operators anyways?
    d
    a
    z
    • 4
    • 6
  • r

    Ray

    07/13/2020, 4:34 AM
    Hi people, I’m using JPA Hibernate, and I have my Entity Foo and Entity Bar, both tables have status column as varchar when I first ran the app. And I could see those tables created. Then I changed the status column type to int for both tables and restart the app, only Bar table’s updated, Foo table’s disappeared I have in my local profile so I can see in the log it says create table Foo and Bar
    spring.jpa.show-sql=true
    spring.jpa.hibernate.ddl-auto=create-drop
    Some posts were saying vaguely the problem is status keyword. what’s the issue?
    k
    m
    • 3
    • 3
  • j

    JP

    07/13/2020, 12:39 PM
    How could one convert the
    try-with-resources
    construct in Java to Kotlin, regarding handling exceptions?
    // Java
    DataSource ds = createDataSource();
    try (Connection connection = ds.getConnection()) {
        // ...
        // just throw exception for simulation
        throw new IllegalStateException()
        // ...
    } catch (SQLException e) {
        e.printStackTrace()
    }
    I’ve tried to use the
    use
    function like this:
    // Kotlin
    val ds: DataSource = createDataSource()
    try {
        dataSource.connection.use { connection ->
            // just throw exception for simulation
            throw IllegalStateException()
        }
    } catch (e: SQLException) {
        e.printStackTrace()
    }
    But
    SQLException
    is not caught, instead, only
    IllegalStateException
    could be caught. How could one catch a
    SQLException
    thrown from
    java.sql.Connection.getConnection()
    gracefully using Kotlin, while, if possible, utilizing the
    use
    function to close the connection?
    a
    l
    j
    • 4
    • 5
  • a

    Alex Ch

    07/13/2020, 1:07 PM
    Please point me to a channel where I can ask questions about best practices to build a library interface? (how to return result/error, can I throw exception, etc.)
    c
    z
    • 3
    • 3
  • n

    Nir

    07/13/2020, 9:11 PM
    Unrelated question. Was going through the scope functions. They all seem to have a logical niche carved for themselves, with one exception,
    with
    . It seems like
    with
    has no real advantage, over the extension function form of
    run
    . Usually flowcharts/blog posts say "use run if you need ?.
    but even if you don't need
    ?.
    , you can just always use
    .run` instead of
    with
    . It seems like it would be preferable if
    with
    did not exist, so that there would just be fewer scope functions to know with no disadvantage. Am I missing something about
    with
    ?
    i
    m
    • 3
    • 11
  • g

    Gyuhyeon

    07/14/2020, 3:43 AM
    Is anyone else also in love with the fact that jackson-module-kotlin latest version doesn't strip out
    is
    prefixes from boolean when serializing into response body json like
    val isValid = true => {"isValid": true}
    while Spring latest version requires that
    is
    prefix is not included when deserializing from request parameters like
    ?valid=true => val isValid = true
    yet
    ?ssValid=true
    fails to map? So I either have to mark every boolean in a 20k commit history enterprise project which is linked with a Rest controller like
    @JsonProperty("valid")
    or change the structure so that when consuming my REST api they have to live with "isFoo" boolean naming while when they send back the request to me they have to change the name like "foo" instead in their request bodies. Absolute bonkers I'm beginning to think maybe using
    is
    prefix in kotlin is simply a horrible idea that I should always stay away from. It causes way too many compatibility issues and headaches due to the compiled java source treating it as
    foo
    with
    isFoo()
    getter.
    d
    • 2
    • 1
  • g

    Gunslingor

    07/14/2020, 4:56 AM
    Is there a way in kotlin to compile just the stuff that's relative to one class? Like if I got DB svr and web svr code in the same codebase and I wanna compile the stuff into separate fat people, I mean fat jars?
    m
    • 2
    • 4
  • p

    Paulius Ruminas

    07/14/2020, 7:34 AM
    Hello, will inline classes stay experimental in Kotlin 1.4?
    :yes: 1
    m
    • 2
    • 1
  • s

    Shreyas Patil

    07/14/2020, 2:20 PM
    I'm working on the Android Library which I'm developing in Kotlin. I defined class with modifier
    internal
    which is hiding that class in Kotlin code. But it's publically visible in Java. How can I avoid that?
    z
    • 2
    • 4
  • d

    dimsuz

    07/14/2020, 2:28 PM
    I see that kotlin compiler doesn't issue a warning for unused functions/classes - only unused variables. I know this because I've enabled
    -Werror
    and then found a few of those unused in a codebase, no errors. Only IDE gives a warning on unused functions/classes. Can I somehow ask compiler to do this too?
    b
    a
    n
    • 4
    • 6
  • g

    Gopal S Akshintala

    07/14/2020, 4:07 PM
    This is NOT tailrec
    tailrec fun TreeNode.findMin(): TreeNode = left?.findMin() ?: this
    But this is:
    tailrec fun TreeNode.findMin(): TreeNode = if (left == null) this else left!!.findMin()
    I am missing the concise syntax, why can’t the compiler smartly make the first one
    tailrec
    c
    p
    • 3
    • 2
  • a

    andylamax

    07/14/2020, 8:12 PM
    Hey there, how can I use R8 in a multiplatform project that target jvm? Anyone?
    g
    • 2
    • 9
  • j

    Joel

    07/14/2020, 8:49 PM
    Good afternoon friends, following up on a question from a few weeks ago, I'd like to override some default
    BigDecimal
    extensions in the
    kotlin
    package:
    operator fun BigDecimal.plus(other: BigDecimal): BigDecimal = add(other, MathContext.DECIMAL128)
    
    operator fun BigDecimal.minus(other: BigDecimal): BigDecimal = subtract(other, MathContext.DECIMAL128)
    
    operator fun BigDecimal.div(other: BigDecimal): BigDecimal = divide(other, MathContext.DECIMAL128)
    
    operator fun BigDecimal.times(other: BigDecimal): BigDecimal = multiply(other, MathContext.DECIMAL128)
    The default implementation for
    div
    is:
    @kotlin.internal.InlineOnly
    public inline operator fun BigDecimal.div(other: BigDecimal): BigDecimal = this.divide(other, RoundingMode.HALF_EVEN)
    This will allow my implementation to always use
    DECIMAL128
    standard math context for all operations, eliminating any precision issues (for example
    1.toBigDecimal() / 3.toBigDecimal()
    results in
    1
    due to rounding. I want to help my engineers avoid this. What is the cleanest way to accomplish this? I tried adding a new file in package
    kotlin
    which works but feels like a code smell.
    g
    • 2
    • 7
  • h

    Hullaballoonatic

    07/14/2020, 11:14 PM
    When i first started my job as a c# developer, I really missed kotlin, because it felt like kotlin had everything c# did and then some, but now there are a handful of things from c# i'd love to see in kotlin:
    val last3 = myList[^3..]
    val first3 = myList[..3]
    
    when (numA) {
       <  numB -> foo()
       == numB -> bar()
       >  numB -> baz()
    }
    
    val defaultInt = default(int)
    to name a few. one of the distinct differences between the languages, though, is that c# does not have the type-erasure that the jvm does, so perhaps that allows for
    default
    e
    • 2
    • 1
  • j

    Joel Pedraza

    07/15/2020, 12:30 AM
    Terminology question. Fork is to join as suspend is to _____ ?
    i
    • 2
    • 2
  • l

    laimiux

    07/15/2020, 1:58 AM
    Is there a way to use
    where
    clause when defining
    typealiases
    ?
    l
    z
    m
    • 4
    • 6
  • w

    Wesley Acheson

    07/15/2020, 9:53 AM
    Hi people I need to work with a java api. I'm storing info in a remote store and also in memory. The interface for the remote store is that it returns a Mono of the value, but if its not found it returns a Mono with the value null. I'm trying to get the in memory implementation to do the same.
    override fun load(id: String): Mono<StoredRequest?> {
            val storedRequest: StoredRequest? = memory[id]
            return Mono.just(null);
        }
    However it doesn't allow me to return a Mono of null here or even return the value from the backing map. As far as I understand the method signature I've given a null should be allowed. Is there any way to force the java like behaviour?
    t
    • 2
    • 7
  • n

    Nir

    07/15/2020, 2:21 PM
    How does one iterate over the mutable properties of a class? I can see that you can do
    for (x in foo::class.memberProperties)
    , but this only allows you to iterate over properties, i.e. no set function is available
    g
    • 2
    • 16
  • g

    Gunslingor

    07/15/2020, 3:01 PM
    File file = new File(
    	getClass().getClassLoader().getResource("database.properties").getFile()
    );
    Is this really the best way to access files in the resources folder?
    n
    t
    • 3
    • 7
  • s

    stephanmg

    07/15/2020, 3:06 PM
    What do you not like about this?
    g
    a
    • 3
    • 62
Powered by Linen
Title
s

stephanmg

07/15/2020, 3:06 PM
What do you not like about this?
g

Gunslingor

07/15/2020, 3:16 PM
for one getClass is ambiguous as heck, no idea what to import.... second, it isn't exactly intuitive, maybe you can clarify what's happening here? third... I could have swarn I was programming in a language recently that let me do something like resource("path from resources root") and I thought it was kotlin... forth, if they are going to strongly recommend organizing a project like this, thought they would make it easy! I don't know, lol
Why do I need to get file after getting resource... does getResource get tacos too? lol
s

stephanmg

07/15/2020, 3:18 PM
well.
I presume the resource does not need to be provided as a file
right?
I remember a syntax like this:
g

Gunslingor

07/15/2020, 3:19 PM
clientDocker.buildImageCmd().pathToDockerfile()
path
s

stephanmg

07/15/2020, 3:20 PM
val file = MyClass::class.java.getResource("database.properties").getFile()
you like that better?
g

Gunslingor

07/15/2020, 3:21 PM
is MyClass just this?
s

stephanmg

07/15/2020, 3:22 PM
It’s the class name
but you could also do this:
this.javaClass.getResource("database.properties").getFile()
I’ve right now no time to answer your question about the internals but if you will find a tone of good explanations via google
g

Gunslingor

07/15/2020, 3:24 PM
I just need the path... I could do ..\..\resources\blah blah... but if I move stuff around later that would suck.
val clientDocker = DockerClass().dockerClient
    val result = clientDocker.infoCmd().exec()
    val file = DockerClass::class.java.getResource("database.properties").file
This works, now I just need the path of it.
s

stephanmg

07/15/2020, 3:26 PM
try . absolutePath
g

Gunslingor

07/15/2020, 3:26 PM
nope, getResource is returning null, what should the path be? "dockerfiles/svrDB" isn't workin
s

stephanmg

07/15/2020, 3:29 PM
Is your problem related to retrieving the resource (Which seems not to work) or you are wondering about the syntax being used?
g

Gunslingor

07/15/2020, 3:29 PM
it isn't working... I assumed because my pathing syntax was wrong
s

stephanmg

07/15/2020, 3:30 PM
so the techniques used are based on reflections
g

Gunslingor

07/15/2020, 3:32 PM
DockerClass::class.java.getResource("svrDB") must not be null at com.newsworthy.build.containers.DockerClass.main(Docker.kt:31) at com.newsworthy.build.containers.DockerKt.main(Docker.kt:40) at com.newsworthy.build.containers.DockerKt.main(Docker.kt) Process finished with exit code 1
s

stephanmg

07/15/2020, 3:37 PM
should read about classloaders and their purpose
similiar in Java too
or C#
g

Gunslingor

07/15/2020, 3:37 PM
ok\
s

stephanmg

07/15/2020, 3:38 PM
maybe somebody else is available to help you out right now
will come back to you alter
later
g

Gunslingor

07/15/2020, 3:38 PM
no worries, break time anyway
a

akatkov

07/15/2020, 5:02 PM
If you're using this in a jar, getting a resource as a file is unsupported, see: https://stackoverflow.com/questions/20389255/reading-a-resource-file-from-within-jar
If not, may be an issue between using the resources in main vs. test
g

Gunslingor

07/15/2020, 6:43 PM
I'm so confused dudes... So what do I do here, I need a path to the svrDB file posted a pic of above... what type of path am I supposed to use in this modern framework?
fun main(){
    val clientDocker = DockerClass().dockerClient
    val result = clientDocker.infoCmd().exec()
    DockerClass().main()
    //clientDocker.buildImageCmd().pathToDockerfile("?????")

}
a

akatkov

07/15/2020, 6:49 PM
is this code in BuildApp.kt?
g

Gunslingor

07/15/2020, 6:49 PM
its in Docker.kt, the file I wanna reference is svrDB
Full code in that file
package com.newsworthy.build.containers

import com.github.dockerjava.core.DefaultDockerClientConfig
import com.github.dockerjava.core.DockerClientConfig
import com.github.dockerjava.core.DockerClientImpl
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient
import com.github.dockerjava.transport.DockerHttpClient
import java.io.File

const val projectName: String = "srcBuild"

class DockerClass {
    private val config: DockerClientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
        .withDockerHost("<tcp://localhost:2375>")
        //.withDockerTlsVerify(true)
        //.withDockerCertPath("/home/user/.docker")
        //.withRegistryUsername("admin")
        //.withRegistryPassword("password")
        //.withRegistryEmail("<mailto:gunslingor@gmail.com|gunslingor@gmail.com>")
        //.withRegistryUrl("<https://index.docker.io/v1/>")
        .build()

    val httpClient: DockerHttpClient = ApacheDockerHttpClient.Builder()
        .dockerHost(config.dockerHost)
        .sslConfig(config.sslConfig)
        .build()

    val dockerClient = DockerClientImpl.getInstance(config, httpClient)!!

    fun main(){
        //val filePath = DockerClass::class.java.getResource("svrDB").file
        //val filePath = (this::class).java.getResource("dockerfiles\\svrDb")
        //print(filePath)


    }
}

fun main(){
    val clientDocker = DockerClass().dockerClient
    val result = clientDocker.infoCmd().exec()
    DockerClass().main()
    //clientDocker.buildImageCmd().pathToDockerfile()

}
a

akatkov

07/15/2020, 6:50 PM
can you move the
svrDb
file to main/resources instead of test/resources?
g

Gunslingor

07/15/2020, 6:51 PM
yes, that is probablyt in error, lol... but if I need to test a resource what happens, I have to put it both?
maybe that was my problem, lol
a

akatkov

07/15/2020, 6:52 PM
yeah, by default, test classes/resources are not accessible in main
you could probably play around with
sourceSets
in gradle to make it work, but wouldn’t recommend necessarily
hard to say without knowing the context, but yeah, could put it in both resources folder or refactor how the file is passed into the DockerClass
g

Gunslingor

07/15/2020, 6:54 PM
I love sources sets, I do see the resources setting and I have used it before... maybe that's the way I recall doing it so easy before... even so, gradle just sets it and it's in the default local so it is already set correctly... I checked the gradle docs and nothing actually tells me how to access em right though.
DockerClass::class.java.getResource("dockerfile/svrDB")
still comes back null
a

akatkov

07/15/2020, 6:55 PM
i see the folder is called
dockerfiles
in your screenshot
g

Gunslingor

07/15/2020, 6:56 PM
fixed, no change... also concerned, even if I get this working it's going to change if I compile to a jar?
a

akatkov

07/15/2020, 6:57 PM
yeah, in a jar, you can only get access to an
InputStream
to it using
getResourceAsStream
if you need it in a literal file, you’d need to write that InputStream to a temporary file and use that
g

Gunslingor

07/15/2020, 6:59 PM
I mean, this function takes a path not a file... so your telling me the path is going to change depending on whether I use a jar or not?
a

akatkov

07/15/2020, 6:59 PM
DockerClass::class.java.classLoader.getResource("dockerfiles/svrDB")
g

Gunslingor

07/15/2020, 7:00 PM
thanks, that did seem to give the path.. in my output folder, interesting
a

akatkov

07/15/2020, 7:00 PM
a jar is basically a zip so there doesn’t exist a straightforward path to your resource
g

Gunslingor

07/15/2020, 7:01 PM
right... not really sure what java does to run it
So I really need a method that will work like this and in a fat jar... this is great for programming, but prod uses fat people jars
thanks though... much appreciated
👍 1
a

akatkov

07/15/2020, 7:04 PM
yeah, to make it work in jars, i recommend trying
getResourceAsStream
, write that to a File (maybe using
File.createTempFile
), then you can pass that path to your function and it’ll work in both dev IDE/prod jar scenarios
g

Gunslingor

07/15/2020, 7:06 PM
weird. Is that really what folks do, isn't copying a file a waste of resources? Guess I'll try it, no worries.
a

akatkov

07/15/2020, 7:07 PM
don’t claim to be an expert with the manipulation of resources like this, but it’s what i’ve found so far in my research
g

Gunslingor

07/15/2020, 7:24 PM
hmmm..... check this out, I'm using ktor and klaxon in my srcWeb project and I noticed this... so there I just have to add this like and ktor seems to be serving up the files via HTTP without issue, whether Jar/War/Normal-whatever... class files?
static("/static") {
    files("build/processedResources/jvm/main")
}
wonder what it's really doing... oh well, I get stuck trying to understand things... time to move on, lol
a

akatkov

07/15/2020, 7:25 PM
hard to say what it’s doing under the hood without looking under the hood lol
g

Gunslingor

07/15/2020, 7:27 PM
no worries, thanks again.
👍 1
View count: 1