How to shadow member function with a custom Kotlin extension function? (like Kotlin stdlib does) - kotlin

I am reading Kotlin in Action 2nd edition.
Chapter 3 says:
If the class has a member function with the same signature as an extension function, the member function always takes precedence
At the same the book demonstrates the CharSequence.split Kotlin's stdlib extension function (which API is less confusing than an API of Java's String#split).
The thing I do not understand is how this split extension functions takes precedence on the following call:
"12.345-6.A".split(".") // <-- Kotlin's extension function gets invoked here even though there is a member function on String class in Java with matching signature
The book also leaves the following comment on this case:
Kotlin hides the confusing method and provides as replacements several overloaded extensions named split that have different arguments
How does Kotlin hide a member function? Can I also shadow some member function which I do not like with my custom extension function? Or it is a trick which is only available to Kotlin language developers?

Actually Kotlin has a separate implementation of CharSequence and String.
These kotlin String/Charsequence does not have its split function. Kotlin team has made all those string implementation functions separately with help of extension functions.Your string will be referring to kotlin String instead of Java String.
If you need to create java String, you need to refer String with package like below.
var str : java.lang.String = java.lang.String("a b c")
str.split("")
Here it will always call Java split function.
Even if you create split function for java.lang.String , it will call only member function as you have read.
member function always takes precedence

Related

Extension function on a generic type

I am new in Kotlin and I am trying to understand type alias and functions.
I have the following example:
interface EmptyInterface
typealias GenericCase<T> = T.(EmptyInterface) -> T
val myFunctionVariable: GenericCase<String> = {
_ -> "Hello world!"
}
So far what I understand is that I extend what ever T is defined with a function that accepts as argument an EmptyInterface and returns a T.
So the myFunctionVariable is a function that should be called passing an EmptyInterface
But the following code does not compile
class a: EmptyInterface
println("${myFunctionVariable(a())}")
I need to pass a String as the first parameter:
class a: EmptyInterface
println("${myFunctionVariable("",a())}")
Why is the string needed as the first parameter? T.(EmptyInterface) -> T which in this case is String.(EmptyInterface) -> String has only 1 parameter.
Could someone please explain this?
The T. in the type T.(EmptyInterface) -> T means that this function is an extension function on T. So the regular way to call this function is to acquire a T instance, and call it on that instance, as if it was a member function. In the case of your example, where you chose T to be a String, you have to call the function on a String instance:
"foo".myFunctionVariable(a())
The syntax you've used is an alternative way to call this extension, passing in the receiver as if it was the first parameter of the function (which, at the bytecode level, it actually is):
myFunctionVariable("foo", a())
If you wish to use your function with this syntax, however, it's better to declare it to take two parameters, as this invocation of an extension function can be quite unexpected.
(There's some more info about how you can go back and forth between a function that's an extension on a type and one that takes it as a first parameter in this answer.
In the type T.(EmptyInterface) -> T, the first T is the receiver: an instance that the function is called upon, and which becomes this within the function definition.  (Similar to an extension function.)
Effectively, the receiver becomes a hidden first parameter to the function; as you discovered, if you try to call the function directly, you'll need to give it explicitly.
The language spec for it is here; some other answers may also help.

Initializing a field member in Kotlin that is a function

New to Kotlin, I have seen this code:
val myModule : Module = module {
viewModel { MyViewModel(get()) }
single { MyRepository() }
}
Looking at the Kotlin docs, it isn't clear to me what the braces mean after "module". Is module a function and the braces are used to initialize the function? If this is true, can you point me to the part in the Kotlin documentation that indicates this? I can't find anything in the docs that shows an example of this. Here is the link:
https://kotlinlang.org/docs/reference/properties.html
Note that your example seems like Koin code.
In a more general sense:
In kotlin when the last parameter of a function is another function ( see Higher order functions) you can put it outside the parenthesis, and if it is the only (non optional) parameter you can omit the parenthesis enterily.
In your example module viewModel and single are functions that take another function as their only parameter, this way you can pass the lambda defining this paramter directly without any parenthesis.
The braces mean that the module function receives a lambda as a parameter. http://kotlinlang.org/docs/reference/lambdas.html#passing-a-lambda-to-the-last-parameter

Explanation on Function literal with receiver in Kotlin

I was following this link https://kotlin.link/articles/DSL-builder-in-Kotlin.html to understand the builder implementation in Kotlin. I didn't understand the methods inside Builder class. Method name() receives Extension Function as an argument which receives nothing and returns String. And the caller calls name { "ABC" }. If the caller is passing String to name method, how does it translate to an Extension method which returns String ?
I tried following Kotlin documentation for Function literals with receivers but all had samples which returns Unit or refers to DSL Builders. Tried googling it as well to understand but no luck in grasping the concept.
The call to name { "ABC" } is a combination of two Kotlin conventions.
There is a convention that if the last parameter to a function is a function you can omit the parenthesis. Also since there are no parameters to the lambda, "ABC" is what is returned by it.
So the caller is actually passing a lambda in the form name ({() -> "ABC"}), rather than a String.
Looking at the example in the link, it doesn't look like the receiver is necessary for name(), which is why it could be misleading.

Kotlin: Why can't I use one of my functions?

I am trying to use one of my defined functions that accepts a string yet the software won't compile.
fun passes(address: String) = Collections.frequency(addresses, address) <= CONNECTIONS_PER_IP
fun passes(remoteAddress: InetSocketAddress) = passes(remoteAddress.hostName)
I can't even call the string function using a custom string, for example passes("127.0.0.1").
None of the following functions can eb called with the arguments supplied.
passes(String) defined in abendigo.Firewall
passes(InetSocketAddress) defined in abendigo.Firewall
I presume you're using java.lang.String instead of kotlin.String in the Kotlin source code. Please use only kotlin.String instead, this is the type that string literals in Kotlin have (but in the bytecode it's still transformed to java.lang.String).
The issue was an import of java.lang.String. For some reason IntelliJ imported it.

Kotlin: Method reference not working?

It seems I'm unable to use a method reference of an object in Kotlin. This feature exists in Java.
For example in Java if I was looping through a string to append each character to a writer:
string.forEach(writer::append);
But in Kotlin using the same syntax does not work because:
For now, Kotlin only supports references to top-level and local functions and members of classes, not individual instances. See the docs here.
So, you can say Writer::append and get a function Writer.(Char) -> Writer, but taking a writer instance and saying writer::append to get a function (Char) -> Writer is not supported at the moment.
Starting from Kotlin 1.1 writer::append is a perfectly valid bound callable reference.
However, you still cannot write string.forEach(writer::append) because Writer#append method returns a Writer instance and forEach expects a function that returns Unit.
I am using Kotlin 1.3 and while referencing a Java method I got a very similar error. As mentioned in this comment, making a lambda and passing it to the forEach method is a good option.
key.forEach { writter.append(it) }
Being it the implicit name of a single parameter.