How to structure functional code in Kotlin? - kotlin

I'm wondering what is the best way to structure functional code in Kotlin.
I don't want to create unnecessary objects (and put functions in a closed scope) to group my functions with. I heard I can group functions by packages and put them in the top level of a package. I've also seen in Arrow library that functions are grouped in interface companion objects as extension functions and this looks the best except the fact I need to create a companion object.
Object way:
object Container {
fun myFunc() = ...
}
...
Container.myFunc()
Package way:
package myPackage
fun myFunc() = ...
...
myPackage.myFunc()
Arrow way:
interface Container {
companion object {
fun Container.myfunc() = ...
}
}
...
Container.myFunc()
What is the best way to structure my functions and group them using Kotlin? I want to keep a pure functional style, avoid creating any sort of objects, and be able to easily navigate to functions by namespaces like:
Person.Repository.getById(id: UUID)

If I understand you correctly, you're looking for the concept of namespaces (structured hierarchical scope for accessing symbols).
Kotlin does not support namespaces, but as you found out, there are different ways of having similar functionality:
object declarations. They pretty much fulfill the needs, however they lead to creation of an actual object in JVM and introduce a new type, which you don't need. The Jetbrains team generally discouraged the use of objects as namespaces, but it's of course still an option. I don't see how companion objects inside interfaces add any value. Maybe the idea is to limit the scope to classes which implement the interface.
Top-level functions. While possible, top-level functions in Kotlin pollute the global namespace, and the call-site does not let you specify where they belong. You could of course do workarounds, but all of them are rather ugly:
Fully qualify the package com.acme.project.myFunc()
Use a deliberately short, but no longer domain-representing package functional.myFunc()
Call function without package, but with prefix package_myFunc()
Extension functions. If the functionality is closely related to the objects it's operating on, extension functions are a good option. You see this for the Kotlin standard collections and all their functional algorithms like map(), filter(), fold() etc.
Global variables. This does not add much over the object approach, just prevents you from introducing a named type. The idea is to create an anymous object implementing one or more interfaces (unfortunately, without interfaces the declared functions are not globally accessible):
interface Functionals {
fun func(): Int
}
val globals = object : Functionals {
override fun func() = 3
}
It is mainly handy if your object implements different interfaces, so that you can pass only a part of the functionality to different modules. Note that the same can be achieved with objects alone, as they can implement interfaces too.

Related

Why do we need an explicit function interface modifier in Kotlin?

consider a SAM defined in Java
public interface Transform {
public String apply(String str);
}
This interface supports lambda to type conversion in Kotlin automatically
fun run(transform: Transform) {
println(transform.apply("world"))
}
run { x -> "Hello $x!!" } // runs fine without any issues
But now consider a Kotlin interface
interface Transform2 {
fun apply(str: String): String
}
Now the only way to invoke the run function would be by creating an anonymous instance of Transform2
run(object : Transform2 {
override fun transform(str: String): String = "hello $str!!"
})
but if we make the Transform2 interface a functional interface then the below is possible
run { str -> "hello $str!!" }
Why the Kotlin compiler cannot automatically type cast lambdas to matching interfaces (just as it does with Java interfaces) without needing to explicitly mark the said interfaces as a functional interface.
I've found some kind of a rationale in a comment in KT-7770:
... treating all the applicable interfaces as SAM might be too
unexpected/implicit: one having a SAM-applicable interface may not
assume that it will be used for SAM-conversions. Thus, adding another
method to the interface becomes more painful since it might require
changing syntax on the call sites (e.g. transforming callable
reference to object literal).
Because of it, current vision is adding some kind of modifier for
interfaces that when being applied:
Adds a check that the interface is a valid SAM
Allows SAM-conversions on call sites for it
Something like this:
fun interface MyRunnable {
fun run()
}
Basically, he is saying that if the SAM conversion were done implicitly by default, and I add some new methods to the interface, the SAM conversions would no longer be performed, and every place that used the conversion needs to be changed. The word "fun" is there to tell the compiler to check that the interface indeed has only one abstract method, and also to tell the call site that this is indeed a SAM interface, and they can expect the author to not suddenly add new abstract methods to the interface, suddenly breaking their code.
The thread goes on to discuss why can't the same argument can't be applied to Java, and the reason essentially boils down to "Java is not Kotlin".
This is speculation, but I strongly suspect one reason is to avoid encouraging the use of functional interfaces over Kotlin's more natural approach.
Functional interfaces are Java's solution to the problem of adding lambdas to the Java language in a way that involved the least change and risk, and the greatest compatibility with what had been best practice in the nearly 20 years that Java had existed without them: the use of anonymous classes implementing named interfaces. It needs umpteen different named interfaces such as Supplier, BiFunction, DoublePredicate… each with their own method and parameter names, each incompatible with all the others — and with all the other interfaces people have developed over the years. (For example, Java has a whole host of interfaces that are effectively one-parameter functions — Function, UnaryOperator, Consumer, Predicate, ActionListener, AWTEventListener… — but are all unrelated and incompatible.) And all this is to make up for the fact that Java doesn't have first-class functions.
Kotlin has first-class functions, which are a much more general, more elegant, and more powerful approach. (For example, you can write a lambda (or function, or function literal) taking a single parameter, and use it anywhere that you need a function taking a single parameter, without worrying about its exact interface. You don't have to choose between similar-looking interfaces, or write your own if there isn't one. And there are none of the hidden gotchas that occur when Java can't infer the correct interface type.) All the standard library uses function types, as does most other Kotlin code people write. And because they're so widely-used, they're widely supported: as part of the Kotlin ecosystem, everyone benefits.
So Kotlin supports functional interfaces mainly for compatibility with Java. Compared to first-class functions, they're basically a hack. A very ingenious and elegant hack, and arguably a necessary one given how important backward compatibility is to the Java platform — but a hack nonetheless. And so I suspect that JetBrains want to encourage people to use function types in preference to them where possible.
In Kotlin, you have to explicitly request features which improve Java compatibility but can lead to worse Kotlin code (such as #JvmStatic for static methods, or casting to java.lang.Object in order to call wait()/notify()). So it fits into the same pattern that you also have to explicitly request a functional interface (by using fun interface).
(See also my previous answer on the subject.)

Kotlin: Idiomatic usage of extension functions - putting extension functions next to the class it extends

I see some usages of Extension functions in Kotlin I don't personally think that makes sense, but it seems that there are some guidelines that "apparently" support it (a matter of interpretation).
Specifically: defining an extension function outside a class (but in the same file):
data class AddressDTO(val state: State,
val zipCode: String,
val city: String,
val streetAddress: String
)
fun AddressDTO.asXyzFormat() = "${streetAddress}\n${city}\n${state.name} $zipCode"
Where the asXyzFormat() is widely used, and cannot be defined as private/internal (but also for the cases it may be).
In my common sense, if you own the code (AddressDTO) and the usage is not local to some class / module (hence behing private/internal) - there is no reason to define an extension function - just define it as a member function of that class.
Edge case: if you want to avoid serialization of the function starting with get - annotate the class to get the desired behavior (e.g. #JsonIgnore on the function). This IMHO still doesn't justify an extension function.
The counter-response I got to this is that the approach of having an extension function of this fashion is supported by the Official Kotlin Coding Conventions. Specifically:
Use extension functions liberally. Every time you have a function that works primarily on an object, consider making it an extension function accepting that object as a receiver.
Source
And:
In particular, when defining extension functions for a class which are relevant for all clients of this class, put them in the same file where the class itself is defined. When defining extension functions that make sense only for a specific client, put them next to the code of that client. Do not create files just to hold "all extensions of Foo".
Source
I'll appreciate any commonly accepted source/reference explaining why it makes more sense to move the function to be a member of the class and/or pragmatic arguments support this separation.
That quote about using extension functions liberally, I'm pretty sure means use them liberally as opposed to top level non-extension functions (not as opposed to making it a member function). It's saying that if a top-level function conceptually works on a target object, prefer the extension function form.
I've searched before for the answer to why you might choose to make a function an extension function instead of a member function when working on a class you own the source code for, and have never found a canonical answer from JetBrains. Here are some reasons I think you might, but some are highly subject to opinion.
Sometimes you want a function that operates on a class with a specific generic type. Think of List<Int>.sum(), which is only available to a subset of Lists, but not a subtype of List.
Interfaces can be thought of as contracts. Functions that do something to an interface may make more sense conceptually since they are not part of the contract. I think this is the rationale for most of the standard library extension functions for Iterable and Sequence. A similar rationale might apply to a data class, if you think of a data class almost like a passive struct.
Extension functions afford the possibility of allowing users to pseudo-override them, but forcing them to do it in an independent way. Suppose your asXyzFormat() were an open member function. In some other module, you receive AddressDTO instances and want to get the XYZ format of them, exactly in the format you expect. But the AddressDTO you receive might have overridden asXyzFormat() and provide you something unexpected, so now you can't trust the function. If you use an extension function, than you allow users to replace asXyzFormat() in their own packages with something applicable to that space, but you can always trust the function asXyzFormat() in the source package.
Similarly for interfaces, a member function with default implementation invites users to override it. As the author of the interface, you may want a reliable function you can use on that interface with expected behavior. Although the end-user can hide your extension in their own module by overloading it, that will have no effect on your own uses of the function.
For what it's worth, I think it would be very rare to choose to make an extension function for a class (not an interface) when you own the source code for it. And I can't think of any examples of that in the standard library. Which leads me to believe that the Coding Conventions document is using the word "class" in a liberal sense that includes interfaces.
Here's a reverse argument…
One of the main reasons for adding extension functions to the language is being able to add functionality to classes from the standard library, and from third-party libraries and other dependencies where you don't control the code and can't add member functions (AKA methods).  I suspect it's mainly those cases that that section of the coding conventions is talking about.
In Java, the only option in this cases is utility methods: static methods, usually in a utility class gathering together lots of such methods, each taking the relevant object as its first parameter:
public static String[] splitOnChar(String str, char separator)
public static boolean isAllDigits(String str)
…and so on, interminably.
The main problem there is that such methods are hard to find (no help from the IDE unless you already know about all the various utility classes).  Also, calling them is long-winded (though it improved a bit once static imports were available).
Kotlin's extension methods are implemented exactly the same way down at the bytecode level, but their syntax is much simpler and exactly like member functions: they're written the same way (with this &c), calling them looks just like calling a member function, and your IDE will suggest them.
(Of course, they have drawbacks, too: no dynamic dispatch, no inheritance or overriding, scoping/import issues, name clashes, references to them are awkward, accessing them from Java or reflection is awkward, and so on.)
So: if the main purpose of extension functions is to substitute for member functions when member functions aren't possible, why would you use them when member functions are possible?!
(To be fair, there are a few reasons why you might want them.  For example, you can make the receiver nullable, which isn't possible with member functions.  But in most cases, they're greatly outweighed by the benefits of a proper member function.)
This means that the vast majority of extension functions are likely to be written for classes that you don't control the source code for, and so you don't have the option of putting them next to the class.

How to inline function map on Flux or Mono object in Kotlin and Project Reactor

I'm trying to develop a demo app using Kotlin and Project Reactor and I want to inline some functions like map on objects like Flux or Mono.
I did like this:
private inline fun Flux<Account>.map(noinline transformer: (Account) -> AccountDTO): Flux<AccountDTO> {
return this.map(transformer)
}
but it's not ok because I'm receiving the following warning from IDEA:
Expected performance impact of inlining 'private open inline fun Flux<Account>.map(noinline transformer: (Account) -> AccountDTO): Flux<AccountDTO> defined in com.freesoft.reactiveaccountservice.api.controller.AccountController' is insignificant. Inlining works best for functions with parameters of functional types.
Does anyone have any idea how I can implement this inline functions or if it matters to implement it?
Tx!
So far as you are just calling the non-inlined map defined in Java, there won't be a benefit. You could in principle look at the Java definition, and translate it to Kotlin, and make that your inlined map's defintion, but (without checking) I'd expect it just to be something like return new MapFlux(...) which probably won't benefit either because the lambda needs to be stored in a field.
So you'd need to reimplement a considerable portion of the library in Kotlin.
Usually, you want to inline lambda functions which are passed into higher-order functions because it reduces the runtime overhead. No anonymous classes and function reference objects will be created during runtime when you inline the lambdas. In your case, inlining doesn't boost performance because it's a regular function. You can read full explanation with examples here

What is the idiomatic way of creating instance of external interface in Kotlin JS

Example:
In #material-ui/core/createMuiTheme.d.ts there are a few interfaces defined, e.g. ThemeOptions and Theme
It's possible to generate koltin bindings using ts2kt and it allows using createMuiTheme function to create Theme from ThemeOptions, but what is a correct [aka type safe] way of instantiating ThemeOptions which is an external interface and it doesn't have a constructor.
I created a data class that implements the interface and instantiate it. Sometimes I need to use the instance as dynamic as it allows 3rd party js code to modify it.
Is this approach any good assuming I don't want to lose type safety and use JsObject/json()/js()?
The described way (implementing an interface by a data class) is good as well as any other way to implement an interface: by usual class, object expression and so on.
You can use jso<ExternalInterface> {}.
Here's an example from the Kotlin wrappers:
https://github.com/karakum-team/kotlin-mui-showcase/blob/main/src/main/kotlin/team/karakum/components/showcases/TextFields.kt
TextField {
asDynamic().InputProps = jso<InputBaseProps> {
startAdornment = InputAdornment.create {
position = InputAdornmentPosition.start
+"kg"
}
}
}

Class vs. Module in VB

What advantage is there, if any, to using Modules rather than classes in VB? How do they differ, and what advantages/disadvantages are there in using modules? In VB or VB.NET, I use both.
(A) Modules
and
(B) Classes with only Shared functions
solve the same problem: Both allow you to logically group a set of functions.
Advantages of using a module:
It allows you to define extension methods.
For someone reading your code, it is immediately obvious that this is not a class representing a group of stateful objects but just a "function container".
Advantages of using a class with shared functions:
It's easy to extend it with instance (= non-shared) variables, functions and properties later on.
So, if you are writing a set of helper functions and want to logically group them (where the concept of a state of this group just doesn't make sense), use a module -- this is exactly what they are here for. On the other hand, if you have a function that conceptually fits to an already existing class, add it as a shared function to that class.
A major difference is that methods in modules can be called globally whereas methods in classes can't. So instead of ModuleName.MyMethod() you can just call MyMethod(). Whether that is an advantage or disadvantage depends on the circumstances.
Module are come earlier and now VB.NET just let it for backward compatibility. Modules and Class are nearly same. You can call Module.Function() directly as it treat as Shared Function in a class. Class you can define Shared Function/Method and additionally can create an instance like Dim c as Class = New Class().
Avoid use of Module, instead use Class. it is good for you to write a better OOP programming.