https://kotlinlang.org logo
Title
n

natpryce

02/04/2019, 8:15 AM
Static imports in Java are not “bad”. Static mutable state can cause problems. Kotlin helps one avoid mutable state, with an emphasis on immutable data and pure functions.
👍 2
☝️ 1
a

Andrew Gazelka

02/04/2019, 3:15 PM
I heard stateful static functions are bad. What if the state is stored in an object? i.e.,
object Test {
  val list = arrayListOf("a","b","c")
}

fun testerSomething() = Test.list.joinToString()
having the function out of the object is esp nice for extension functions
n

natpryce

02/04/2019, 3:16 PM
The state in that example is still global.
But yes, global mutable state is often problematic
But Kotlin’s extension functions do not, by themselves, give you mutable state.
a

Andrew Gazelka

02/04/2019, 3:19 PM
so it would be bad to have
fun testerAdd() = Test.list.add("something")
i.e., for some type of manager class
n

natpryce

02/04/2019, 3:19 PM
Yes. In that case, the Test object is a mutable singleton.
That doesn’t encapsulate it’s (global) mutable state
My point is: it’s not the testerAdd function that’s the problem, it’s the Test object.
a

Andrew Gazelka

02/04/2019, 3:21 PM
oh I see because list should be private if it is in a class/object
n

natpryce

02/04/2019, 3:21 PM
I’d say that Test should be immutable.
a

Andrew Gazelka

02/04/2019, 3:23 PM
well this would be for a manager class where I would have
fun add(stored: Something)
fun update(stored: Something)
fun remove(stored: Something)
fun get(id: String): Something?
so it would need to be mutable
n

natpryce

02/04/2019, 3:23 PM
Then I’d advise against making it a global singleton.
a

Andrew Gazelka

02/04/2019, 3:24 PM
instead make the storage map private and have all those functions as part of the object?
n

natpryce

02/04/2019, 3:24 PM
Don’t make it an object declaration
a

Andrew Gazelka

02/04/2019, 3:24 PM
oh so the map would not be in a class
(or an object)
n

natpryce

02/04/2019, 3:25 PM
I mean… don’t make it an object declaration. Define a class. Pass references to instances of that class around. That way, you can control the how the mutability affects different parts of the system explicitly.
a

Andrew Gazelka

02/04/2019, 3:26 PM
ok thanks