https://kotlinlang.org logo
Title
y

Yuriy Kulikov

04/24/2018, 8:53 AM
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

edwardwongtl

04/24/2018, 8:56 AM
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

gildor

04/24/2018, 8:58 AM
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

petersommerhoff

04/24/2018, 8:58 AM
1) The Kotlin standard library usually groups related extension into the same file 2) Well. what @gildor said, he was faster 🙂
g

gildor

04/24/2018, 9:08 AM
Also interesting thing about class level extensions, if this extension is public, some other code can use it too:
class Foo {
   fun String.addFoo() = "${javaClass.simpleName} $this"
}
// Some other file:
val foo = Foo()
with(foo) {
    println("bar".addFoo()) // Foo bar
}
👍 2
y

Yuriy Kulikov

04/24/2018, 9:12 AM
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

gildor

04/24/2018, 4:05 PM
do you mean something like:
(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

ilya.gorbunov

04/24/2018, 7:06 PM
In Kotlin you can use
run { }
to invoke a lambda function immediately.
👏 2