Rookie question. If I want to provide some code in...
# getting-started
m
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
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
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
I still think there's more nuance to it than that...but that last bullet's a good point
m
Agreed - property “calls” should at least be idempotent. 🙂
g
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
The weirdest thing would be defining a val using a verb in the name:
val computeHeight
n
hah, yeah, don't do that 🙂
m
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()
)