https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
a

Anton Afanasev

06/20/2022, 1:23 PM
I remember kmm used to have some restrictions having default arguments and swift/objective-c. Is it still a case? Recently I tried that out and it seem that kotlin native compiler does respsect function with default argument. So this:
Copy code
fun sendMessage(text: String, customAttributes: Map<String, String> = emptyMap())
translated to this:
Copy code
func sendMessage(text: String, customAttributes: [String : String] = [:])
Am I seeing write? kotlin 1.6.10
k

kpgalligan

06/20/2022, 2:44 PM
Copy code
func sendMessage(text: String, customAttributes: [String : String] = [:])
That’s swift. The Kotlin compiler would be generating objc. Where do you see that? Default parameters aren’t available, unless something I’m not aware of happened.
a

Anton Afanasev

06/20/2022, 3:01 PM
That is really odd. I would expect to see Kotlin compiler generating obj-c as well. Instead, I am seeing a swift generated code... I see that by using the regular XCode
Jump To Definition
tool. Thats weird...
Interestingly, if I pass an empty map as a default argument swift would not force me to provide a value for this argument. So I can do something like that: common:
Copy code
fun sendMessage(text: String, customAttributes: Map<String, String> = emptyMap())
ios/swift
Copy code
client.sendMessage(text: "Hello")
No warnings or errors. But that only work with emptyMap. If I go and define some other default argument, lets say:
Copy code
fun sendMessage(text: String, customAttributes: Map<String, String> = mapOf("a" to "b")
They default argument will be ignored and the value of
customAttributes
in that case will be empty map as well. Is it possible that K\N compiler always treat a map argument as an emptyMap, unless actual value is provided?
r

Rick Clephas

06/20/2022, 4:08 PM
Cool! Didn’t know about this. This is actually part of the Swift - ObjC interop:
An argument whose Objective-C type is an NSDictionary defaults to nil if the NSDictionary is nullable and [:] if the NSDictionary is non-nullable, under the following conditions:
• the argument label contains the word “options” or “attributes”, or the two words “user info” one after another
• the argument label is empty and the method base name ends with the word “options” or “attributes”, or the two words “user info” one after another
https://github.com/apple/swift/blob/main/docs/CToSwiftNameTranslation.md#default-argument-values
😳 1
👍 1
Another nice one is:
A final argument that is a nullable function or block pointer defaults to nil.
Copy code
fun doSomething(block: (() -> Unit)?) = TODO()
can be called from Swift like:
Copy code
doSomething() // default nil
doSomething { }
k

kpgalligan

06/20/2022, 4:34 PM
Huh, interesting
I didn’t know that either
a

Anton Afanasev

06/20/2022, 5:57 PM
Thanks @Rick Clephas and @kpgalligan Thats a nice thing to know. Sounds like some sort of
easter egg
65 Views