Olaf Gottschalk
03/24/2023, 6:21 PMinfix fun <T> String.blah(processor: (String)->T): T
infix fun <T> String?.blah(processor: (String)->T): T?
Normally, such problems can be fixed by adding a specific @JvmName
annotation to at least one of the two methods - but in this case you get an error, stating "'@JvmName' annotation is not applicable to this declaration". This is quite a downer.. why is that and how can I make this compile? I thought an extension function is nothing special at all, in my case a function with two arguments...
Any chance I might get this working? Thanks!Youssef Shoaib [MOD]
03/24/2023, 6:35 PMunit: Unit = Unit
to the nullable function (so that even though the non-null is now higher priority, the nullable will still be called for nullable arguments)Olaf Gottschalk
03/24/2023, 6:43 PMunit: Unit = Unit
... can you put that in context, please. Does that fix my problem?Youssef Shoaib [MOD]
03/24/2023, 10:06 PMinterface Test {
infix fun <T> String.blah(processor: (String)-> T): T = processor(this)
@Suppress("INAPPLICABLE_INFIX_MODIFIER")
infix fun <T> String?.blah(processor: (String)-> T, unit: Unit = Unit): T? = this?.let(processor)
}
class TestImpl: Test
fun main(){
val nullable: String? = null
val test = with(TestImpl()) { "hello" blah { it } }
val test2 = with(TestImpl()) { nullable blah { it } }
print(test)
print(test2)
}
the suppress is needed since the unit parameter makes the function have 3 params. I don't think there's a way around that, but thankfully the suppress is sufficient to not cause any issuesOlaf Gottschalk
03/25/2023, 10:40 AM@JvmInline
class as a wrapper around my nullable Receiver - technically this does exactly what I wanted, when you look at the bytecode there's a function with a name blah_something
for my nullable Receiver.
What I still would like to understand from the makers of the Kotlin compiler is, why I cannot just use @JvmName
on my second infix fun...Youssef Shoaib [MOD]
03/25/2023, 11:30 AMJvmName
annotation.Olaf Gottschalk
03/25/2023, 11:36 AMYoussef Shoaib [MOD]
03/25/2023, 1:16 PMinterface Test {
infix fun <T> String.blah(processor: (String)-> T): T = processor(this)
@Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("blahNullable")
infix fun <T> String?.blah(processor: (String)-> T): T? = this?.let(processor)
}
interface Test
context(Test)
infix fun <T> String.blah(processor: (String)-> T): T = processor(this)
context(Test) @JvmName("blahNullable")
infix fun <T> String?.blah(processor: (String)-> T): T? = this?.let(processor)
(You can adapt this one to use inheritance by having 2 methods with different names named something other than blah within Test, and then have the contextual blah extensions call out to each apt method).Olaf Gottschalk
03/25/2023, 1:33 PMYoussef Shoaib [MOD]
03/25/2023, 4:30 PMOlaf Gottschalk
03/27/2023, 9:00 AMYoussef Shoaib [MOD]
03/27/2023, 12:13 PM