Does Kotlin have an identity function? - kotlin

Scala has a generic identity function in the Predef:
def identity[A](x: A): A
Does Kotlin have a similar facility in the standard library? Of course I could simply use { it } instead, but I find identity easier to read, and instantiating all those lambdas is a little wasteful.
I must be able to use this identity function in places where a function (Foo) -> Foo is expected, for any type Foo. Is such a function even possible in Kotlin's type system? (In the case of Scala, there is an implicit conversion that wraps the method inside a function object or something.)

If you need to pass the identity function as a parameter to another function, you can simply use { it }. For example, it you have a List<List<String>> and want to flatten it to a List<String>, you could use:
list.flatMap(identity)
where identity is the identity function. This can be written as:
list.flatMap { it }
This is equivalent to:
list.flatMap { x -> x }
The alternative would be to define the identity function somewhere, such as:
val identity: (List<String>) -> List<String> = { it }
But we can't create a generic val, so we would have to define an identity function for each type. The solution, (as it is done in Java Function interface) is to define it as a constant function:
fun <A> identity(): (A) -> A = { it }
and use it as:
list.flatMap(identity)
Of course, it is much easier to write:
list.flatMap { it }
Declaring an identity function once for all (that would work for all types) is not possible because it would have to be parameterized. What is possible is to use a function returning this identity function:
fun <T> identity(): (T) -> T = { it }
Although it does the job, it is not very helpful since one has now to write:
list.flatMap(identity())

There's no such function at the moment, but you can easily define it yourself:
fun <T> identity(x: T): T = x
If you think there are enough use cases for this function to be declared in Kotlin standard library, please file an issue at youtrack.jetbrains.com. Thanks!

Related

Are Kotlin scope function blocks effectively inline?

I'm writing a Kotlin inline class to make Decimal4J more convenient without instantiating any objects. I'm worried that scope functions might create lambda objects, thereby making the whole thing pointless.
Consider the function compareTo in the following example.
/* imports and whatnot */
#JvmInline
value class Quantity(val basis: Long) {
companion object {
val scale: Int = 12
val metrics: ScaleMetrics = Scales.getScaleMetrics(scale)
val arithmetic: DecimalArithmetic = metrics.defaultArithmetic
}
operator fun compareTo(alt: Number): Int {
with(arithmetic) {
val normal = when (alt) {
is Double -> fromDouble(alt)
is Float -> fromFloat(alt)
is Long -> fromLong(alt)
is BigDecimal -> fromBigDecimal(alt)
is BigInteger -> fromBigInteger(alt)
else -> fromLong(alt.toLong())
}
return compare(basis, normal)
}
}
}
Does the with(arithmetic) scope create a lambda in the heap? The docs on kotlinlang.org consistently refer to the scoped code as a lambda expression. Is there any way to use scope functions without creating objects?
All of the built-in scoping functions, including with, are marked inline, which means the implementation gets planted directly in the code that's calling it. Once that happens, the lambda call can be optimized away.
To be more concrete, here's the implementation of with (with the Kotlin contracts stuff removed, since that's not relevant here)
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
return receiver.block()
}
Extension methods are, and always have been, syntax sugar resolved at compile time, so this is effectively
public inline fun <T, R> with(receiver: T, block: (T) -> R): R {
return block(receiver) // (with `this` renamed by the compiler)
}
So when we call
operator fun compareTo(alt: Number): Int {
with (arithmetic) {
println("Hi :)")
println(foobar()) // Assuming foobar is a method on arithmetic
}
}
The inline will transform this into
operator fun compareTo(alt: Number): Int {
({
println("Hi :)")
println(it.foobar()) // Assuming foobar is a method on arithmetic
})(arithmetic)
}
And any optimizer worth its salt can see that this is a function that's immediately evaluated, so we should go ahead and do that now. What we end up with is
operator fun compareTo(alt: Number): Int {
println("Hi :)")
println(arithmetic.foobar()) // Assuming foobar is a method on arithmetic
}
which is what you would have written to begin with.
So, tl;dr, the compiler is smart enough to figure it out. You don't have to worry about it. It's one of the perks of working in a high-level language.
By the way, this isn't just abstract. I just compiled the above code on my own machine and then decompiled the JVM bytecode to see what it really did. It was quite a bit noisier (since the JVM, by necessity, has a lot of noise), but there was no lambda object allocated, and the function was just one straight shot that calls println twice.
In case you're interested, Kotlin takes this example function
fun compareTo(alt: Number): Unit {
return with(arithmetic) {
println("Hi :)")
println(foobar())
}
}
to this Java, after being decompiled,
public static final void compareTo-impl(long arg0, #NotNull Number alt) {
Intrinsics.checkNotNullParameter((Object)alt, (String)"alt");
long l = arithmetic;
boolean bl = false;
boolean bl2 = false;
long $this$compareTo_impl_u24lambda_u2d0 = l;
boolean bl3 = false;
String string = "Hi :)";
boolean bl4 = false;
System.out.println((Object)string);
int n = so_quant.foobar-impl($this$compareTo_impl_u24lambda_u2d0);
bl4 = false;
System.out.println(n);
}
Quite a bit noisier, but the idea is exactly the same. And all of those pointless local variables will be taken care of by a good JIT engine.
Just some additional info to help clear up the terminology that led to your confusion.
The word “lambda” is defined as a syntax for writing a function. The word does not describe a function itself, so the word lambda has nothing to do with whether a function object is being allocated or not.
In Kotlin, there are multiple different syntaxes you can choose from to define or refer to a function. Lambda is only one of these.
// lambda assigned to variable
val x: (String) -> Unit = {
println(it)
}
// anonymous function assigned to variable
val y: (String) -> Unit = fun(input: String) {
println(input)
}
// reference to existing named function assigned to variable
val z: (String) -> Unit = ::println
// lambda passed to higher order function
“Hello World”.let { println(it) }
// anonymous function passed to higher order function
“Hello World”.let(fun(input: Any) { println(input) })
// reference to existing named function passed to higher order function
“Hello World”.let(::println)
// existing functional reference passed to higher order function
“Hello World”.let(x)
There is actually no such thing as a lambda object that can be passed around. The object is a function that could have been defined using any of the above syntaxes. Once a functional reference exists, the syntax that was used to create it is irrelevant.
With inline higher order functions, as the standard library scope functions are, the compiler optimizes away the creation of the functional object altogether. Of the four higher order calls in my example above, the first three will compile to the same thing. The last is a bit different because the function x already exists so it will be x itself that is invoked in the inlined code. Its contents don’t get hoisted out and called directly in the inlined code.
The advantage of using lambda syntax for higher order inline function calls is that it enables you to use keywords for the outer scope (non-local returns), such as return, continue, or break.

Extension function from a generic interface

Consider the following interface
interface EntityConverter<in A, out B> {
fun A.convert(): B
fun List<A>.convert(): List<B> = this.map { it.convert() }
}
I want to use it in a spring boot application where specific implementations get injected so that the extension function becomes usable on the type.
However this doesn't work. The compiler does not resolve the extension function.
Note that you're defining extension functions that are also member functions of the EntityConverter type. You should take a look at this part of the doc for information about how this works.
Essentially, in order to use them, you need 2 instances in scope:
the dispatch receiver (an instance of EntityConverter<A, B>)
the extension receiver (an instance of A or List<A>, where A matches the first type parameter of the EntityConverter in scope)
You can use with() to bring the EntityConverter in scope so you can use convert on your other instances using the usual . syntax:
val converter = object : EntityConverter<Int, String> {
override fun Int.convert() = "#$this"
}
val list = listOf(1, 2, 3)
val convertedList = with(converter) {
list.convert()
}
println(convertedList) // prints [#1, #2, #3]
Now you have to decide whether this kind of usage pattern is what makes most sense for your use case. If you'd prefer more "classic" calls without extensions (converter.convert(a) returning a B), you can declare your functions as regular methods taking an argument instead of a receiver.
Bonus: functional interface
As a side note, if you add the fun keyword in front of your EntityConverter interface, you can create instances of it very easily like this:
val converter = EntityConverter<Int, String> { "#$this" }
This is because your converter interface only has a single abstract method, making it easy to implement with a single lambda. See the docs about functional interfaces.
I'm not sure if you can mention extension functions as a part of interface, because it's like static functions.
I'd recommend to put "common" function in interface with A typed parameter. Then just put extension method for list nearby.
interface EntityConverter<in A, out B> {
fun convert(a: A): B
}
fun <A, B> EntityConverter<A, B>.convert(list: List<A>): List<B> = list.map { convert(it) }
Update
I wasn't aware about possibility of inheritance of extension methods in Kotlin. And about its overriding as well. So my answer could be just an alternative of using extension methods.

Kotlin Higher-order functions

I am new in function programming language and I just came through a new concept called Higher-order function.
I have seen some of the Higher-order functions such as filter(), map(), flatMap(), take(), drop() and zip(). I only able to get details of this higher-order functions.
My question is: These are the only higher-order functions available in kotlin or there are more higher-order functions also available.
I am not sure, Can we also create higher-order functions for personal use or not?
Thanks in advance.
Yes, there are many more higher-order functions in Kotlin, e.g., apply, also, lazy, let, onSuccess, recover, recoverCatching, repeat, run, runCatching, suspend, with, use. Explore the reference documentation for functions that consume other functions as values, e.g., https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/, https://kotlinlang.org/docs/tutorials/kotlin-for-py/functional-programming.html#nice-utility-functions.
Yes, users can define higher-order functions. Refer to https://kotlinlang.org/docs/reference/lambdas.html for info about how to define and use higher-order functions.
As mentioned in the Comparison to Java page's 4th point, Kotlin has proper function types, as opposed to Java's SAM-conversions.
What I mean by that is if you want to accept a function or some sort of code in Java that you can call inside a function you need an external interface having exactly 1 method which is aware of the return type and the parameter signature.
For example in Java:
// You can't create this unless you create FuncInterface defining its parameter and return type
MyFuncInterface a = (s) -> System.out.println(s);
interface MyFuncInterface {
public void myMethod(String s);
}
// now call a like
a.myMethod("Hello World"); // will print: Hello World
a.myMethod("Test"); // will print: Test
While it is not the case in kotlin, you can create lambda without creating an interface here.
For example same code in Kotlin could be converted into:
val a: (String) -> Unit = { println(it) }
// or like this: val a: (String) -> Unit = { s -> println(s) }
// call like this
a("Hello World") // will print: Hello World
a("Test") // will print: Test
Since Kotlin has proper function types, you can make a function accept a function type or return one, which is then be called a Higher-Order Function.
Concept is similar:
// This is a higher order functon, takes a callable function `f`
fun operatesFOn(num1: Int, num2: Int, f: (Int, Int) -> Int) {
// this types are useful as callbacks, instead of taking nums and passing them
// you can compute heavy tasks and when they complete call f with the result
return f(num1, num2)
}
// lambda can be put outside the parentheses if it is last parameter
// also is another higher order function which calls the lambda passed with the object it was called on as a parameter
operatesFOn(3, 4) { a, b -> a + b }.also { println(it) } // prints: 7
operatesFOn(5, 7) { a, b -> a * b }.also { println(it) } // prints: 35
There are some other cool modifiers as well for higher order functions like the inline modifier.
inline fun operatesFOn(num1: Int, num2: Int, f: (Int, Int) -> Int) {
return f(num1, num2)
}
The above one will work similar but the lambda will instead be inlined at the call-site in compile time, to decrease the call-stack increasing the performance. as mentioned in the docs as well:
Using higher-order functions imposes certain runtime penalties: each function is an object, and it captures a closure, i.e. those variables that are accessed in the body of the function. Memory allocations (both for function objects and classes) and virtual calls introduce runtime overhead.

is there any way I send a nullable Function<T,R> as parameter in Kotlin?

I am trying to use the public interface Function (as I learned it in Java) in Kotlin.
For this I created my method
fun foo(input: List<String>, modifier1: Function<List<String>>? = null){
}
as far I remember here I should be able to do modifier1.apply(input)
but seems like it is not possible (it is possible to do modifier1.apply{input} though)
Reading more about it I found this:
Kotlin: how to pass a function as parameter to another?
So I changed my method signature to this:
fun foo(input:String, modifier2: (List<String>) -> (List<String>){
}
Here I am able to do modifier2(input)
and I can call foo this way
service.foo(input, ::myModifierFunction)
where
fun myModifierFunction(input:List<String>):List<String>{
//do something
return input
}
So far this seems possible but it is not acceptable to have the function reference as nullable, is there any way I can do that? or use Function ?
You were using kotlin.Function instead of java.util.function.Function in your first example. Note that the latter takes 2 generic types: 1 for the incoming parameter and 1 for the resulting one.
The apply method you saw is the default Kotlin one: apply, not the one of Java's Function-interface.
If you really want to have the Java-function as nullable type the following should work:
fun foo(input: List<String>, modifier1: java.util.function.Function<List<String>, List<String>>? = null) {
modifier1?.apply(input) ?: TODO("what should be done if there wasn't passed any function?")
}
Kotlin variant for the same:
fun foo(input: List<String>, modifier1: ((List<String>) -> List<String>)? = null) {
modifier1?.invoke(input) ?: TODO("what should be done if there wasn't passed any function?")
}
Maybe also a default function, such as { it } instead of null might better suite your needs? (Java variant would be Function.identity()):
// java modifier1 : Function<List<String>, List<String>> = Function.identity()
// kotlin modifier1 : (List<String>) -> List<String> = { it }
You can make the reference nullable simply with ? — the only wrinkle is that the whole function type needs to be in parens first:
fun foo(input: String, modifier2: ((List<String>) -> List<String>)? = null) {
}
As required, modifier2 is optional; if specified, it may contain null, or it may contain a function taking and returning a list of strings.
As mentioned in another answer, kotlin.Function is not the same as java.util.function.Function — though in practice you shouldn't need to refer to either directly, as the -> notation is simpler.
If you want to pass in a function that takes List<String> as its parameter and returns nothing meaningful, the type for you is Function1<List<String>, Unit>. The method name for invoking a function is invoke(), which you could also do with just regular parentheses, if it wasn't nullable. All in all, your code could look something like this:
fun foo(input: List<String>, modifier1: Function1<List<String>, Unit>? = null) {
modifier1?.invoke(input)
}
The 1 in the typename of Function1 means that it's a one parameter function, there's also Function0, Function2, etc.
The Function type on its own is not something you can use to call that function, as it's an empty marker interface. All functions implement this regardless of how many parameters they have.

Difference between function receiver and extension function

I was reading about Kotlin and did not quite get the idea
from What I understood extension function gives ability to a class with new functionality without having to inherit from the class
and what is receiver the same except it can be assigned to variable
Is there anything else about it?
Can someone give some examples on it
Extension functions:
Like Swift and C#, Kotlin provides the ability to extend a class with new functionality without having to modify the class or inherit from the class.
You might wonder why? Because we cannot edit and add functions to the language or SDK classes. So we end up creating Util classes in Java. I believe all the projects have a bunch of *Utils classes to put the helper methods that are used at multiple places in the code base. Extensions functions help to fix this Util problem.
How do we write a helper method in Java to find whether the given long value refers to today?
public class DateUtils {
public static boolean isToday(long when) {
// logic ...
}
}
And we call that method by passing the long value as an argument:
void someFunc(long when) {
boolean isToday = DateUtils.isToday(when);
}
In Kotlin, we can extend the Long class to include the isToday() function in it. And we can call the isToday() function on the Long value itself like any other member functions in the class.
// Extension function
fun Long.isToday(): Boolean {
// logic ...
}
fun someFunc(time: Long) {
val isToday = time.isToday()
}
Compared to the Util methods, Kotlin provides a much richer syntax using the Extension functions.
This improves the readability of the code which in turns improves its maintainability. And we get a little help from the code completion of the IDE. So we don't have to remember which Util class to use for the desired function.
Under the hood, Kotlin compiler generates the static helper methods as though we had written them as Java static Util methods. So we get this nice and richer syntax in Kotlin without sacrificing any performance.
Similar to functions, Kotlin also supports extension properties where we can add a property to an existing class.
Higher order functions:
A higher-order function is a function that takes functions as parameters, or returns a function.
Lets look at how a higher order function is written.
fun execute(x: Int, y: Int, op: (Int, Int) -> Int): Int {
return op(x, y)
}
Here the third parameter ( op ) is a function and so it makes this function a higher order function. The type of the parameter op is a function that takes 2 Ints as parameter and returns a Int.
To invoke this Higher order function, we can pass a function or a lambda expression:
execute(5, 5) { a, b -> a + b }
Receiver (or Function literal with Receiver or Lambda with Recevier):
A Higher order function that takes an extension function as its parameter is called Lambda with Receiver.
Let's look at the implementation of the apply function which is available in the Kotlin standard library.
inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
The function we pass to this apply function is actually an extension function to the type T. So in the lambda function, we can access the properties and the functions of the type T as though we are writing this function inside class T itself.
Here the generic type T is the receiver and we are passing a lambda function, hence the name Lambda with Receiver.
Another Example:
inline fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) {
beginTransaction()
try {
func()
setTransactionSuccessful()
} finally {
endTransaction()
}
}
Here, the inTransaction() is an Extension function to the SQLiteDatabase class and the parameter of the inTransaction() function is also an extension function to the SQLiteDatabase class. Here SQLiteDatabase is the receiver, for the lambda that is passed as the argument.
To invoke that function:
db.inTransaction {
delete( ... )
}
Here the delete() is the function of the SQLiteDatabase class and since the lambda we pass is an Extension function to the receiver SQLiteDatabase we can access the delete function without any additional qualifiers with it, as though we are calling the function from inside the SQLiteDatabase class itself.
While #Bob's answer is far more informative on Kotlin than could I hope to be, including extension functions, it doesn't directly refer to the comparison between "function literals with receiver" as described in https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver and extension functions (https://kotlinlang.org/docs/reference/extensions.html). I.e. the difference between:
val isEven: Int.() -> Boolean = { this % 2 == 0 }
and
fun Int.isEven(): Boolean = this % 2 == 0
The receiver part of the name refers to both of these syntaxes receiving the base Int argument as this.
As I understand it, the difference between the two is simply between one being an expression confirming to a function type and the other a declaration. Functionally they are equivalent and can both be called as:
when { myNumber.isEven() -> doSomething(myNumber) }
but one is intended for use in extension libraries, while the other is typically intended for use as an argument for a function with a function-type parameter, particularly the Kotlin builder DSLs.