calling overloaded function with default arguments in Kotlin - oop

Hi i am confused in invoking concept of a function with default arguments in case of function overloading.
My use case is -
i have two functions with same name(function overloading) and i have added few default arguments, so it is not clear which function will be called.
Example-
fun add(a:Int, b:Int=2, c:Int=2):Int
{
return a+b+c
}
fun add(a:Int, b:Int=1):Int
{
return a+b
}
Now i am calling
add(5)
add(5,2)
which method should be called.
if i check
fun foo(p1:Int,p2:String?=null)
fun foo(p1:Int,p2:Int=0)
this will cause of
"overload resolution ambiguity" error.
But in my case every time fun add(a:Int, b:Int=1):Int
{
return a+b
}
is called.
So how ?

2nd function (fun add(a:Int, b:Int=1):Int) is called because it is a closer match (less parameter difference) as zapl pointed out.
DETAILS:
Resolution of overloaded method calls with default params is described in Kotlinlang spec:
The candidate with the least number of non-specified default
parameters is a more specific candidate
So when you call add(5), then the number of non-specified default parameters is:
2 for fun add(a:Int, b:Int=2, c:Int=2):Int
1 for fun add(a:Int, b:Int=1):Int
That's why the 2nd function is called. Based on the same logic, the 2nd function wins also when add(5,2) is called.
But when you have that 3rd function (fun foo(p1:Int,p2:String?=null)), the compiler can't decide which one to call, because the parameter difference is the same. Based on docs:
If there are still more than one most specific candidate afterwards, this is an overload ambiguity which must be reported as a compile-time error.

Related

Any significant differences between lambda expressions & anonymous function in Kotlin?

Kotlin has these 2 features and I think there're no significant differences between these two
regardless of :
syntax
// lambda
val toUpper = { value: String ->
if (value.isEmpty()) "empty value"
else value.toUpperCase()
}
// anonymous func
val toUpper = fun(value: String): String {
if (value.isEmpty()) return "empty value"
else return value.toUpperCase()
}
flexibility to use return statement on anonymous function
I'm still digesting these features and hope you guys can help me pass through it.
Thanks.
Two differences according to Kotlin Reference:
(I think the more significant one out of the two) An anonymous function is still a function, so returning from it behaves the same as returning from any function. Returning from a lambda, however, actually returns from the function enclosing the lambda.
The return type of a lambda is inferred, while you can explicitly specify a return type for an anonymous function.
This website states: "Lambdas Expressions are essentially anonymous functions that we can treat as values – we can, for example, pass them as arguments to methods, return them, or do any other thing we could do with a normal object." (link)
So the answer is no, there isn't a difference between the two, they are interchangeable. Both of the codes you show above, will in the end return the same value to that variable
Besides the differences pointed by #jingx, you can not local return from a lambda that is not inlined.
So, the next snippet will not compile unless you add inline to the extension() function, thus, instructing the compiler to copy the function's content whenever it is referenced:
fun doSomethingWithLambda(){
10.extension{
if(it == 10)
return//compiler error
}
println("hello")
}
fun Int.extension(f: (Int)->Unit){
f(this)
}

switchIfEmpty is always called

I have a method like this:
fun getActiveVersionWithCacheMiss(type: String): Mono<ActiveVersion> {
return activeVersionRepository.findByType(type)
.switchIfEmpty(
Mono.defer(return persist(ActiveVersion(type,1)))
)
}
persist method is a simple method that saves active version:
fun persist(activeVersion: ActiveVersion): Mono<ActiveVersion>{...}
In my test I mocked activeVersionRepository to return a simple value for findByType. During debug activeVersionRepository.findByType(type).block() evaluates to a value and is definitely not empty.
I'm wondering why despite using defer switchIfEmpty is still called?
The problem is return. The argument of switchIfEmpty needs to be evaluated regardless of whether findByType emits a value, which means the argument of defer needs to be evaluated, and return will return out of the entire function getActiveVersionWithCacheMiss.
Though I don't see how this code can compile; return persist(...) doesn't have a value which Mono.defer can use. Do you actually have braces {}, not parentheses () somewhere?

When do I use another function without paramters in Kotlin?

I'm a novice of Kotlin.
I found that I can use another function without parameters even if it has.
Let me know when I can use it.
Q1) Why can I use 2 types? (with parameters & without parameters) Is it Kotlin's feature?
Q2) What does it mean? ((Result!) -> Unit)!
It seems you are confused, you can never use a function without arguments. If the function has arguments then you have to fill the slot somehow.
The closest thing that could relate to what you are referring to is default values for arguments.
fun example(boolean: Boolean = true) {}
example()
example(true)
example(false)
You can omit the argument because it has defaulted in the function signature.
The documentation
What you are showing in the image file is a lambda.
In the first example:
signIn(listener: Session...)
That seems to be a callback. So it is gonna be an interface or maybe an abstract class called when some async operation is finished.
The second example, it is the callback implemented as a lambda
signIn() { result ->
//do something
}
In Kotlin the last argument if it is a lambda or something that can be implemented as a lambda can be moved out of the parenthesis for syntactic sugar. A lambda is like an anonymous function, it is a literal of a function.
By example you can declare a lambda:
val lambda = {text: String -> text.lenght % 2 == 0}
fun setRuleForText(rule: (String)-> Boolean) {...}
setRuleForText(lambda)
setRuleForText() { text: String
text.isNotEmpty()
}
In this case, the argument is a kotlin function. The argument rule is a function that receives a String as an argument and returns Boolean. Something to point out is that expressions return the last written value without the need for the reserved return word.
This is the documentation. And here you can see from a good source more about functions (the author is a Kotlin certified trained by Jetbrains)
In your case (Result) -> Unit means the lambda should receive a Result type as argument and then return Unit (unit is like void in Java but is more than that), no explicit return type.
signIn() { result ->
//do something
}
Most of the types, the argument on lambdas is inferred automatically, but if not, then
signIn() { result: Result ->
//do something
}
Both of the listed functions take a parameter.
The first is:
signIn(listener: Session.SignInListener!)
That takes a single parameter, of type Session.SignInListener.  (The ! means that Kotlin doesn't know whether it's nullable or not, because it's from Java and isn't annotated.)
The other is:
signIn {...} (listener: ((Result!) -> Unit)!)
That's the IDE's representation of the function with this signature:
signIn(listener: ((Result!) -> Unit)!)
That takes a single parameter, which is a function type (see below).
The reason the IDE shows it with braces is that in Kotlin, if the last parameter to a function is a lambda, you can move it outside the parentheses.  So a call like this:
signIn({ println(it) })
could equally well be written like this:
signIn() { println(it) }
The two forms mean exactly the same.  And, further, if the lambda is the only parameter, you can omit the parens entirely:
signIn { println(it) }
Again, it means exactly the same thing.
That syntax allows you to write functions that look like new language syntax.  For example:
repeat (10) {
// ...
}
looks like a new form of loop construct, but it's really just a function called repeat, which takes two parameter (an integer, and a lambda).
OK, let's look at that function type: ((Result!) -> Unit)!
That's the type of a function which takes one parameter of type Result, and returns Unit (i.e. nothing useful; think of it as the equivalent of void).  Again, it's complicated because Kotlin doesn't know about the nullability; both the Result parameter and the parameter holding this function have !s to indicate this.  (Without them, it would just be (Result) -> Unit.)

Extension function with different signature is confusing with different extension function in kotlin

class Example
fun main(){
val example: Example = Example()
// what function i am calling is it fun Example.extensionFun() ?
// Or is it Example.extensionFun(string: String) ?
example.extensionFun()
}
// first extension function
fun Example.extensionFun(){
println("Hey i'm first extension function")
}
// second extension function
fun Example.extensionFun(testArgument: String = "test argument "){ // argument just to change the function signature
println("Hey i'm second extension function ")
}
In the above example i have created two extension function with the same name but different signature.
When i try to call ->
example.extensionFun()
then IDE just calls the "fun Example.extensionFun()"
but even if i try to call
fun Example.extensionFun(testArgument: String ="test argument")
by using code completion pop up and selecting second extension function it is again calling
fun Example.extensionFun()
and thus it left me single way to call the second extension function which is by passing the different value for the testArgumet (argument). for eg.
example.extensionFun("different value")
but there is many cases where we don't want to change the default value of the function parameter when we are calling it.
I think i found a bug but kindly please share your opinion
When it's ambiguous, the compiler calls the overload that has fewer arguments. In fact, I don't think it even generates overloads for function signatures that are already explicitly declared. They should probably provide a compiler warning to let you know the default value is pointless, but maybe that was deemed too expensive for compile times.
Your only option is to use a different function name to break the ambiguity.

Why do Kotlin/Java functions look so different in real use from documentation?

For example here is all() in action:
fun Shop.checkAllCustomersAreFrom(city: City): Boolean =
customers.all { it.city == city }
And here is the equivalent from the kotlin documentation:
inline fun <T> Iterable<T>.all(
predicate: (T) -> Boolean
): Boolean
Can someone please explain each part of the second code block and why it's written like that?
Apologies if this is a basic question, but if I learn this it will be much easier to read documentation.
Let's break it down, shall we?
inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean
|--1--|-2-|-3-|-----4-----|-5-|----6-----|------7-------|----8----|
This function is inline. This means that its body essentially gets copy-pasted to the call site at compile time, as an optimization measure (used in this case because it has a lambda parameter).
Declares a function.
Type parameter list, this function has one generic type parameter called T.
This is an extension function, and this is its receiver, i.e. the type being extended. This function will be callable on any Iterable<T> as if it was a member function. The Iterable that it was called on can be accessed inside the function's body as this.
The name of the function.
The name of the first and only parameter of the function (if we don't count the receiver, which is technically also a parameter).
The type of the function's parameter. This is a function type, which describes a function that takes a single T parameter, and returns a Boolean. This can be a reference to a regular function that has this signature, but the expectation with collection functions such as this is that most of the time this will be a lambda.
The return type of the function.
inline - Take the body of this function and put it where it is being called when compiled instead of calling a function.
fun - function declaration
- generic type called T
Iterable - class we are adding an extension function too. (If it is not inline read static function)
all - name of the function
predicate - parameter named predicate
: (T) -> Boolean - Lambda Type takes a T as a parameter and returns a Boolean. Usually in the form { it == foo }
: Boolean - Returns a Boolean