Hello everyone, our team is new to Kotlin (we are ...
# announcements
y
Hello everyone, our team is new to Kotlin (we are used to Java) and since we have to started to write new stuff in Kotlin, we cannot seem to agree on some best practices. Small stuff, mostly: 1. Where to put higher order functions and data classes - is it ok to write them directly in the same file or they have to be moved to a new file? Pro/contra? 2. Extension functions - is it ok to declare member extension functions in classes (i.e. extension functions which have access to class properties)? Or should be prefer higher end extension functions? Example: // declared in the class, access a class property private fun String.toTypeElement(): TypeElement { return processingEnv.elementUtils.getTypeElement(this) } -vs- // declared outside, class property must be passed as a parameter fun String.toTypeElement(processingEnv: ProcessingEnvironment): TypeElement { return processingEnv.elementUtils.getTypeElement(this) } Thanks a lot:-)
e
1. For functions, depends on its usage, just put them in related files. For data classes, I usually put them inside the same file
1
g
1. https://kotlinlang.org/docs/reference/coding-conventions.html#source-file-organization 2. Depends on case. If extension function is used only inside class and even have dependency to this class, I would prefer to use class level extension, also more efficient (just + method in class instead of + 1 class and 1 method for top level function) Class level extensions is good way to reduce extension visibility, even better than private file level extension
p
1) The Kotlin standard library usually groups related extension into the same file 2) Well. what @gildor said, he was faster 🙂
g
Also interesting thing about class level extensions, if this extension is public, some other code can use it too:
Copy code
class Foo {
   fun String.addFoo() = "${javaClass.simpleName} $this"
}
// Some other file:
val foo = Foo()
with(foo) {
    println("bar".addFoo()) // Foo bar
}
👍 2
y
Thanks, this was very helpful:-) I think this covers all my questions:-)
BTW, what do you think about immediately invoked functions in Kotlin?
2
g
do you mean something like:
Copy code
(fun() { println("do something" })()
// or with lambda
({ println("do something") })()
Like in JS? I just don’t see good use cases for them, in JS it’s a way to create visibility scope, but I’m not sure how this can be useful in Kotlin
i
In Kotlin you can use
run { }
to invoke a lambda function immediately.
👏 2