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
a

Amir Eldor

09/23/2020, 8:14 PM
Hello. I'm trying to do something like this and not sure what I'm doing. I want to have a Factory of, let's say, Ship. A Game has a mutable list (or whatever) of Ships so I can track all the Ships in my game (more in thread) -->
The Factory gets a reference to Game when I first create it and when building a Ship the Factory registers the Ship in its Game reference. However, the developer can still create classes of Ship outside the factory. I know I can give Ship a private constructor, but how would I allow the factory to create Ships that way? If I use a companion object I will need to provide it with the Game reference each time and it kind of loses the purpose of creating the Factory with the Game reference once. In C++land I'd probably use friend or something like that. How do you do that in Kotlin? Thanks.
Or maybe there's a smarter way to solve the "let's track all Ships" problem
n

nanodeath

09/23/2020, 8:34 PM
However, the developer can still create classes of Ship outside the factory.
is this a feature or a bug
a

Amir Eldor

09/23/2020, 8:42 PM
It's a bug as this way Game will not track the new Ship
That's why I want to centralize the creation of Ship in a Factory with a reference to a game (there may be different games at the same time :()
Maybe there's a trick with the
internal
keyword, but maybe I'm barking at the wrong tree
n

nanodeath

09/23/2020, 8:49 PM
depends on whether you want people to be able to subclass Ship. if no, then saying
class Ship internal constructor(...)
should be sufficient, then making
ShipFactory.newShip(...)
public
if yes (subclassing permitted), you maybe could make
Ship
itself accept
Game
as a constructor argument that Ship registers with in the constructor, but...passing
this
to other objects from a constructor is problematic from various perspectives (security, exception-handling)
or finally, just say "hey you have to call
Game.addEntity(ship)
or it ain't gonna work"
a

Amir Eldor

09/23/2020, 8:53 PM
Ok, cool, so two question:
I made the internal Ship class inside package
a.stuff.game
, but when I created a Ship instance in
a.stuff.somethingelse
the compiler did not complain. Is this expected as the
a.stuff
is common?
n

nanodeath

09/23/2020, 8:55 PM
internal
works pretty differently from
package private
--
internal
is accessible anywhere in the entire "compilation unit", e.g. your library/engine
if your game and engine are in the same compilation unit and you're trying to keep yourself from calling the Ship constructor directly...that's going to require more thought
internal is documented here
a

Amir Eldor

09/23/2020, 8:57 PM
Yeah I've read this, by 'module' they mean "compilation unit"?
internal
— any client inside this module who sees the declaring class sees its
internal
members;
n

nanodeath

09/23/2020, 8:57 PM
yeah, module as in like...a Gradle project/subproject
a

Amir Eldor

09/23/2020, 8:57 PM
I mistook that for package, alright. Thanks
n

nanodeath

09/23/2020, 8:57 PM
I keep thinking "package" but that's a ridiculously overloaded term
I don't care much for Scala but it's ridiculously fine-grained access controls were nice sometimes 🙂
a

Amir Eldor

09/23/2020, 8:59 PM
I didn't have the pleasure to play with Scala, not sure if I will 😅
Regarding Ship registering itself in game in a constructor, there's no real safe way to do that because the Ship's
this
is incomplete
I read about some lateinit magic, but not sure if that's a thing
n

nanodeath

09/23/2020, 9:01 PM
lateinit is for certain var fields set outside the constructor
a

Amir Eldor

09/23/2020, 9:01 PM
And well, bottom line, I think the best way is just to register the Ship manually after creating it or inside a Factory - OR go the ECS route and be a happier person
n

nanodeath

09/23/2020, 9:02 PM
incidentally, the ECS route also probably requires you explicitly registering some things with the World. I'm writing an ECS for KorGE right now and running into that -- systems and components have to be manually registered with World which sucks
a

Amir Eldor

09/23/2020, 9:04 PM
Hello KorGE, nice to meet you.
Although I'm creating something a bit different
v

Vampire

09/23/2020, 10:49 PM
Make the constructor private and make the factory method in the companion object
n

nanodeath

09/23/2020, 11:40 PM
I've found
private
to be way stricter than Java's
private
when it comes to inner classes and the like
v

Vampire

09/24/2020, 9:32 AM
Even if so, Companion object can pretty well access the private constructor.
a

Amir Eldor

09/24/2020, 4:10 PM
@Vampire can I create a companion object with a reference to a
Game
? so every call to companion's buildShip could reference that Game I initially gave?
v

Vampire

09/24/2020, 5:17 PM
You can set a property of the companion object
a

Amir Eldor

09/24/2020, 7:16 PM
Like that!
v

Vampire

09/24/2020, 7:36 PM
Yeah, that works too. I had something in mind like (untested written on mobile)
kt
class Ship private constructor() : Tickable {
    companion object {
        lateinit val game: Game
        fun create() = Ship().also(game::register)
    }

    override fun tick() {
        println("tock")
    }
}

...
Ship.game = Game()
Ship.create()
a

Amir Eldor

09/24/2020, 7:41 PM
Thanks, looks cool! But this way Ship is tied to a single Game instance, right? I might have another game running in parallel which needs ships created in it and not the former.
v

Vampire

09/24/2020, 7:54 PM
Yeah, then the property approach doesn't work of course, so something like you have or like this:
Yeah, that works too. I had something in mind like (untested written on mobile)
```kt
class Ship private constructor() : Tickable {
    companion object {
        fun producer(game: Game) : () -> Ship = {
            Ship().also(game::register)
        }
    }

    override fun tick() {
        println("tock")
    }
}

...
Ship.game = Game()
Ship.create()
a

Amir Eldor

09/25/2020, 12:10 AM
thanks, I'll look into that fancy .also syntax too