https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Michael Böiers

04/19/2021, 4:39 PM
Rookie question. If I want to provide some code in a class that just returns something, how do I do it? a) Define a function naming the data returned:
fun parsedElements()
b) Define a function naming the data returned prefixed with get (since as per coding conventions functions should incorporate a verb):
fun getParsedElements()
c) Define a read-only property naming the data returned:
val parsedElements: List<String> get() = …
What’s considered best practice, does it depend on “how dynamic” the code is?
I’m leaning towards just using properties for these kinds of getters, usually they contain very little code that access other “proper” properties and does simple conversions. However, the client may be surprised depending on the usage. For example, using such properties as when subjects does not support smart casting.
n

nanodeath

04/19/2021, 4:47 PM
if it accepts 0 parameters, you do have 4 options: fun, val, val get, lazy val.
fun
if you want the caller to treat it as a calculation, val if it's cheap and likely to be used (and immutable), val get if it's cheap and might be used, and val lazy if it's expensive (and immutable)
the more basic question of "is this a 0-arg fun or a val" is a tricky one, though, and isn't always obvious
m

Michael Böiers

04/19/2021, 4:49 PM
I’d say that if it’s a lazy immutable val based on other immutable data (property), then it should be a val by lazy. I wonder whether smart casts would work for that …
Actually the code conventions do say something about this. I missed it when browsing the document for the first time.
n

nanodeath

04/19/2021, 5:04 PM
I still think there's more nuance to it than that...but that last bullet's a good point
m

Michael Böiers

04/19/2021, 5:04 PM
Agreed - property “calls” should at least be idempotent. 🙂
g

geepawhill

04/19/2021, 5:06 PM
A lot has to do with trust-of-your-clients. Because most of us grew up in other languages, most of us treat val x differently from fun x(), especially w.r.t. caching. I sometimes use a fun instead of a val get just to signal it's a computation not a field.
m

Michael Böiers

04/19/2021, 5:21 PM
The weirdest thing would be defining a val using a verb in the name:
val computeHeight
n

nanodeath

04/19/2021, 5:29 PM
hah, yeah, don't do that 🙂
m

Michael Böiers

04/19/2021, 5:39 PM
I’m not that kind of rookie … 😉 But on a more serious note, the notion that all functions must incorporate a verb gives me pause. Either that means that all my getter funs should start with “get”, or all of these kinds of getter funs should be vals …
My take on it is that for these kind of functions that compute values we should name them like a val (noun).
Or just turn the verb into an adjective (e.g.
fun derivedHeight()
)