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
j

Jordan Carlyon

05/24/2022, 3:41 PM
I am having some trouble with visibility modifiers. Basically I want a public getter method with a private setter for subclasses of a parent class. The issue is if that parent class has a private variable it is not able to be set from the child classes so I have to have the parent have a public variable for the child classes to use it but now the var is public so the getter is useless. In Java this was possible with the package-private modifier which in Kotlin has been changed to module-private so do I really need to create a new module just to hide some
vars
?
e

ephemient

05/24/2022, 3:45 PM
private for subclassees
isn't that "protected"?
j

Jordan Carlyon

05/24/2022, 3:47 PM
Yeah but it cannot be used on top level declarations
I can work around that in an annoying and messy way though
c

Casey Brooks

05/24/2022, 3:48 PM
Yeah, I think you’re looking to use
protected
on the
set
method of it
e

ephemient

05/24/2022, 3:53 PM
fyi, if you're just doing the default (get/set field) you can leave out the bodies,
public var someValue: String = ""
    protected set
is equivalent to the definition in the previous image
j

Jordan Carlyon

05/24/2022, 4:06 PM
the parent classes
someValue
can be modified by anyone though
oh I see, the set and get syntax is very strange. set and get are implied to belong to the field...because the syntax is underneath it? Not really clear on the scoping at play here
c

Casey Brooks

05/24/2022, 4:15 PM
Java’s package-private doesn’t protect against that either, though. Anyone could create the same package and access all the package-private members. And if someone is really determined to change the property, they can eve. bypass
private
fields with reflection.
internal
is the closest analog Kotlin has to package-private, except that it actually does give strong guarantees around encapsulation in different modules It’s difficult to truly ensure that a field is never modified except by your own code, so the better route isn’t to forcibly hide those fields, bur rather provide sufficient documentation to let consumers know when they should and should not modify it, so they can make the decision for themselves. Using opt-in annotations on those APIs can help make sure that the library users are aware of the concerns
j

Jordan Carlyon

05/24/2022, 4:15 PM
How does get() work? The docs claim that it is a property on any var but I cannot just paste a get() to random vars in main() {} it gives an error
I don't really care about that though because I control the package, I just don't want any consumers outside that package modifying it
c

Casey Brooks

05/24/2022, 4:17 PM
Properties in Kotlin are not the same as Fields in java. Rather, a Kotlin property is more like a Java getter/setter function. The docs may clear it up for you https://kotlinlang.org/docs/properties.html#getters-and-setters
j

Jordan Carlyon

05/24/2022, 4:20 PM
Where is the get syntax defined? It looks like it can be named anything according to the docs but the compiler only allows "get"
e

ephemient

05/24/2022, 4:22 PM
it is not indentation sensitive, but context sensitive.
get
and
set
immediately following a property declaration have special meaning, otherwise they don't. but by convention they are indented to visually mark them as belonging to the property
c

Casey Brooks

05/24/2022, 4:22 PM
The property itself can be named whatever you want (
val stringRepresentation: String
is the property).
get()
and
set(value)
is the specific syntax for customizing the accessors of the property. Anyone accessing the property with
myClass.stringRepresentation
will not care whether the property internally uses the
get()
or
set(value)
accessors or not
e

ephemient

05/24/2022, 4:23 PM
(well, they also have meaning as annotation use-site targets, but that's in a different unambiguous context)
j

Jordan Carlyon

05/24/2022, 4:26 PM
ok weird so get and set have to be named get and set and get has to come before set
actually the order doesn't even matter just the names
e

ephemient

05/24/2022, 4:28 PM
like many of Kotlin's keywords, they are soft keywords: they have special meaning in specific context only
c

Casey Brooks

05/24/2022, 4:34 PM
With property accessors, you’re not defining your own functions, you’re using language keywords. The compiler creates the appropriate functions (and maybe a Field) for you in the Java bytecode using the name of the property they’re attached to. It’s a bit weird at first if you’re thinking of it like a Java Field, but if you get used to the fact that a property is shorthand syntax for get/set functions, it will make more sense. And Kotlin is literally creating standard bean-style functions based on the properties, see here how you cannot write a custom
getSomeValue()
method because the compiler is already creating a method with that name from the property
j

Jordan Carlyon

05/24/2022, 4:36 PM
seems like there is a ton of soft and fuzzy logic in Kotlin
makes it really hard to read the docs, are there any other docs that explain things more thoroughly? Like what is actually happening
e

ephemient

05/24/2022, 4:40 PM
soft keywords are not unique to Kotlin; Scala has many, Python has a few, and Java is considering them
it is not "soft and fuzzy logic" by any means - it is 100% defined in the grammar
j

Jordan Carlyon

05/24/2022, 4:41 PM
anyways it seems like what I want to do isn't possible in kotlin. I just wanted to make an enum or sealed class with a public getter private setter
e

ephemient

05/24/2022, 4:42 PM
"public getter private setter" is literally
public var property: Type
    private set
it sounds like what you want isn't "private", but more like "protected" or "internal"?
j

Jordan Carlyon

05/24/2022, 4:43 PM
yes, useable for children which are enums and sealed classes
e

ephemient

05/24/2022, 4:43 PM
then that is
protected
, not
private
.
j

Jordan Carlyon

05/24/2022, 4:43 PM
protected doesn't work because they are top level members
so essentially I wouldn't even be using sealed classes or enums at this point, just deconstructing them and reconstructing them with open vars or something similar
e

ephemient

05/24/2022, 4:44 PM
you have a top-level mutable property? that is bad design, and cannot participate in the class hierarchy
but top-level
private
is really "file-private", so that does give you some options
j

Jordan Carlyon

05/24/2022, 4:45 PM
I want a top level property that can be modified based on which type the class is
e

ephemient

05/24/2022, 4:45 PM
just to clarify. top-level means "outside of any class", e.g. at the file level. is this really what you mean?
j

Jordan Carlyon

05/24/2022, 4:46 PM
reading the kotlin docs it looks like top level meant at the top level of the class ie
class  Test {
   var topLevel

    class subClass {

     }
}
c

Chris Lee

05/24/2022, 4:47 PM
class Foo {
  private val onlyVisibleInThisClass : String
  protected val alsoVisibleToSubclasses : String
  internal val visibleToEverythingInThisModule : String
  public val visibleToEverything : String	
}
e

ephemient

05/24/2022, 4:47 PM
where in the docs does it say that?
j

Jordan Carlyon

05/24/2022, 4:49 PM
I cannot find it now but that is how it was appearing to work earlier when I tried to use this for sealed classes
c

Chris Lee

05/24/2022, 4:50 PM
is the issue perhaps with nested/inner classes vs inheritance? in your example subClass is NOT a subclass, it’s a nested class. It’s only a subclass if it inherits, as in:
class subClass : Test()
j

Jordan Carlyon

05/24/2022, 4:52 PM
I think in a sealed class they are all inheriting by some fuzzy implied logic
c

Chris Lee

05/24/2022, 4:53 PM
no. they are inheriting by what you specify as the parent class.
j

Jordan Carlyon

05/24/2022, 4:54 PM
I don't think that's accurate
c

Chris Lee

05/24/2022, 4:54 PM
it is. sealed classes reflect an inheritance hierarchy.
j

Jordan Carlyon

05/24/2022, 4:55 PM
There's some weird dual return type inheritence structure going on
c

Chris Lee

05/24/2022, 4:55 PM
no. implement with standard inheritance.
j

Jordan Carlyon

05/24/2022, 4:55 PM
ok
so it sounds like I am not specifying it, it's being inherited
c

Chris Lee

05/24/2022, 4:56 PM
if you don’t specify the inheritance there is no inheritance relationship.
e

ephemient

05/24/2022, 4:56 PM
they are only inheriting if you declare them as inheriting. the structure is unrelated.
j

Jordan Carlyon

05/24/2022, 4:56 PM
sealed class SealedClass() {
    object Child
}
Child is a subclass of SealedClass
I didn't specify that, it was implied by the structure of the class
e

ephemient

05/24/2022, 4:57 PM
that is only a nested class. you need to state
Child : SealedClass()
to make it a child. it does not matter if it is nested or not.
c

Casey Brooks

05/24/2022, 4:57 PM
A sealed class can have nested classes defined without them being subclasses. You have to explicitly extend the parent class for the class relationship to take effect
👀 1
c

Chris Lee

05/24/2022, 4:58 PM
public abstract class BaseClass() {
    
}

public sealed class Child1 : BaseClass() {
    
}

public sealed class Child2 : BaseClass() {
}
e

ephemient

05/24/2022, 4:58 PM
exactly. it doesn't matter whether
Child1
and
Child2
are nested inside of
BaseClass
or not
c

Chris Lee

05/24/2022, 4:59 PM
yep. this is equivalent:
public abstract class BaseClass() {
    public sealed class Child1 : BaseClass() {

    }

    public sealed class Child2 : BaseClass() {

    }
}
j

Jordan Carlyon

05/24/2022, 4:59 PM
Ok I see the kotlin compiler is having trouble distinguishing this
e

ephemient

05/24/2022, 4:59 PM
it is not trouble - it is intentional, and the same as other languages
c

Casey Brooks

05/24/2022, 4:59 PM
This behavior is also different from Java. In Kotlin, a class defined inside another is by default like a Java static inner class. You can use
inner class
keyword to make it like the default Java nested classes
e

ephemient

05/24/2022, 5:00 PM
inner classes are a type of nested class - but still not a child class
j

Jordan Carlyon

05/24/2022, 5:00 PM
thanks
e

ephemient

05/24/2022, 5:00 PM
Java:
public class Parent {
    static class Nested extends Parent {}
    class Inner extends Parent {}
}
without
extends Parent
, they are only nested, not children
j

Jordan Carlyon

05/24/2022, 5:01 PM
yes I prefer the java syntax, it's much more clear what is happening there
kotlin just makes everything look like a return type
I really dislike that about kotlin, they try to fold all the naming and syntax conventions into a small numbers of things that have many different contextual meanings
it makes the code much less readable
c

Casey Brooks

05/24/2022, 5:03 PM
Most newer languages are doing the same thing though. It makes things a lot nicer in a world with type inference https://elizarov.medium.com/types-are-moving-to-the-right-22c0ef31dd4a
Just takes some getting used to
Anytime you switch languages, it’s going to feel uncomfortable at first. But once you get used to Kotlin you’ll find it’s an objectively better-designed language than Java in most situations, being overall more concise and the intent of your code more clear
❤️ 4