# Proposal: mixfix function syntax

**URL:** <https://discuss.kotlinlang.org/t/proposal-mixfix-function-syntax/22435>\
**Category:** Language Design\
**Created:** [July 16, 2021, 7:46am UTC](https://discuss.kotlinlang.org/t/proposal-mixfix-function-syntax/22435 "2021-07-16T07:46:05Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![Josef-Vonasek](https://avatars.discourse-cdn.com/v4/letter/j/41988e/32.png) [@Josef-Vonasek](https://discuss.kotlinlang.org/u/Josef-Vonasek)\
**Post date:** [July 16, 2021, 7:46am UTC](https://discuss.kotlinlang.org/t/proposal-mixfix-function-syntax/22435/1 "2021-07-16T07:46:05Z")

</div>

Currently, when a function takes more than one callback, you end up with the following code:

```kotlin
myTry({ 
  do something 
}, { 
  alert("Exception Caught $message")
}) { 
  close handles... 
}

```

However, it would be much more nicer to write it as

```kotlin
myTry { 
  do something 
} myCatch { 
  alert("Exception Caught $message") 
} myFinally { 
  close handles... 
}

```

Surprisingly, this feature would not require almost any modifications to Kotlin API, as function argument names can be used as keywords:

```kotlin
fun myTry(fn: Fn, myCatch: Fn, myFinally: Fn) = ...

myTry({ a }, { b }, { c }) == myTry { a } myCatch { b } myFinally { c }

```

---

<div class="post-metadata">

**Author:** ![broot](https://avatars.discourse-cdn.com/v4/letter/b/a88e57/32.png) [@broot](https://discuss.kotlinlang.org/u/broot)\
**Post date:** [July 16, 2021, 7:55am UTC](https://discuss.kotlinlang.org/t/proposal-mixfix-function-syntax/22435/2 "2021-07-16T07:55:06Z")

</div>

While I really love the idea, I often would like to design an `api {} like {} this {}` or declare a function with multiple lambdas, I see one problem. How do you distinguish if this is a function that accepts `myTry` and `myCatch` lambdas or `myCatch` is an infix function running on the result of `myTry`?

---

<div class="post-metadata">

**Author:** ![Josef-Vonasek](https://avatars.discourse-cdn.com/v4/letter/j/41988e/32.png) [@Josef-Vonasek](https://discuss.kotlinlang.org/u/Josef-Vonasek)\
**Post date:** [July 16, 2021, 8:07am UTC](https://discuss.kotlinlang.org/t/proposal-mixfix-function-syntax/22435/3 "2021-07-16T08:07:11Z")

</div>

Hi! I have not given much thought yet to the implementation details.

However:

1. I believe that `mixfix` arguments should have always priority over `infix` methods
2. Perhaps the ambiguity is manageable, similar to multiple `this` in scope.
3. Alternatively, the syntax could be `.. myCatch = { .. } myFinally = { .. }`.

---

<div class="post-metadata">

**Author:** ![broot](https://avatars.discourse-cdn.com/v4/letter/b/a88e57/32.png) [@broot](https://discuss.kotlinlang.org/u/broot)\
**Post date:** [July 16, 2021, 8:35am UTC](https://discuss.kotlinlang.org/t/proposal-mixfix-function-syntax/22435/4 "2021-07-16T08:35:37Z")

</div>

Implementation is another problem, because I guess the compiler parses the code to abstract from without the knowledge about available functions and their args, so it can’t know if this is `myTry(myCatch)` or `myTry().myCatch()`.

But I’m not really talking about the implementation, but about the concept itself. Even from the developer perspective it is not clear, what this code does/is. I think ambiguity on variables (`this`, local variable vs property, etc). and functions (overloads) is much simpler than ambiguity on what the code actually is.

But as I said, I think it would be an awesome feature, so maybe this is just a matter of finding the right syntax. Also, I have almost zero experience in designing programming languages, so it doesn’t really matter what I think 😉

---

<div class="post-metadata">

**Author:** ![kyay10](https://avatars.discourse-cdn.com/v4/letter/k/c57346/32.png) [@kyay10](https://discuss.kotlinlang.org/u/kyay10)\
**Post date:** [July 16, 2021, 11:30am UTC](https://discuss.kotlinlang.org/t/proposal-mixfix-function-syntax/22435/5 "2021-07-16T11:30:50Z")

</div>

This can actually be done today in a DSL-style kind of thing, but it has some performance overhead since it has to pass lambdas as objects around. [This](https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS41LjIwIiwicGxhdGZvcm0iOiJqYXZhIiwiYXJncyI6IiIsImpzQ29kZSI6IiIsIm5vbmVNYXJrZXJzIjp0cnVlLCJ0aGVtZSI6ImlkZWEiLCJjb2RlIjoiZnVuIG1haW4oKSB7XG4gICAgdmFsIG5vcm1hbFRyeVN1Y2Nlc3M6IEludCA9IHRyeSB7XG4gICAgICAgID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2YWwgX2RhdGE6IEFueT8pe1xuICAgIGlubGluZSB2YWwgZGF0YTogRGF0YSBnZXQoKSA9IF9kYXRhIGFzIERhdGFcbn1cblxuaW5saW5lIGZ1biA8TmV4dCwgRGF0YT4gTXVsdGlmaXhQYXJ0T2YoZGF0YTogRGF0YSk6IE11bHRpZml4UGFydDxOZXh0LCBEYXRhPiA9IE11bHRpZml4UGFydChkYXRhKVxuXG5vYmplY3QgTXlUcnkge1xuICAgIG9iamVjdCBNeUNhdGNoXG4gICAgb2JqZWN0IE15RmluYWxseVxufVxuXG5mdW4gPFQ+IG15VHJ5KHRyeUJsb2NrOiAoKSAtPiBUKTogTXVsdGlmaXhQYXJ0PE15VHJ5Lk15Q2F0Y2gsICgpIC0+IFQ+ID0gTXVsdGlmaXhQYXJ0T2YodHJ5QmxvY2spXG5pbmxpbmUgaW5maXggZnVuIDxUPiBNdWx0aWZpeFBhcnQ8TXlUcnkuTXlDYXRjaCwgKCkgLT4gVD4ubXlDYXRjaChjcm9zc2lubGluZSBjYXRjaEJsb2NrOiAoVGhyb3dhYmxlKSAtPiBUKTogTXVsdGlmaXhQYXJ0PE15VHJ5Lk15RmluYWxseSwgKCkgLT4gVD4ge1xuICAgIHJldHVybiBNdWx0aWZpeFBhcnRPZiB7XG4gICAgICAgIHRyeSB7XG4gICAgICAgICAgICBkYXRhKClcbiAgICAgICAgfSBjYXRjaChlOiBUaHJvd2FibGUpIHtcbiAgICAgICAgICAgIGNhdGNoQmxvY2soZSlcbiAgICAgICAgfVxuICAgIH1cbn1cbmlubGluZSBpbmZpeCBmdW4gPFQ+IE11bHRpZml4UGFydDxNeVRyeS5NeUZpbmFsbHksICgpIC0+IFQ+Lm15RmluYWxseShmaW5hbGx5QmxvY2s6ICgpIC0+IFVuaXQpOiBUIHtcbiAgICB2YWwgcmVzdWx0ID0gZGF0YSgpXG4gICAgZmluYWxseUJsb2NrKClcbiAgICByZXR1cm4gcmVzdWx0XG59In0=) is a valid and extensible implementation of this idea:

```auto
fun main() {
    val normalTrySuccess: Int = try {
        42
    } catch(e: Throwable) {
        println(e)
        5
    } finally {
        println("Done!")
    }
    val normalTryFail: String = try {
        "Success"
    } catch(e: Throwable) {
        println(e)
        "Failed"
    } finally {
        println("Done!")
    }
    val myTrySuccess: Int = myTry {
        42
    } myCatch {
        println(it)
        5
    } myFinally {
        println("Done!")
    }
    val myTryFail: String = myTry {
        "Success"
    } myCatch {
        println(it)
        "Failed"
    } myFinally {
        println("Done!")
    }
    println(normalTrySuccess)
    println(normalTryFail)
    println(myTrySuccess)
    println(myTryFail)
}

@JvmInline
value class MultifixPart<Next, Data> @PublishedApi internal constructor(@PublishedApi internal val _data: Any?){
    inline val data: Data get() = _data as Data
}

inline fun <Next, Data> MultifixPartOf(data: Data): MultifixPart<Next, Data> = MultifixPart(data)

object MyTry {
    object MyCatch
    object MyFinally
}

fun <T> myTry(tryBlock: () -> T): MultifixPart<MyTry.MyCatch, () -> T> = MultifixPartOf(tryBlock)
inline infix fun <T> MultifixPart<MyTry.MyCatch, () -> T>.myCatch(crossinline catchBlock: (Throwable) -> T): MultifixPart<MyTry.MyFinally, () -> T> {
    return MultifixPartOf {
        try {
            data()
        } catch(e: Throwable) {
            catchBlock(e)
        }
    }
}
inline infix fun <T> MultifixPart<MyTry.MyFinally, () -> T>.myFinally(finallyBlock: () -> Unit): T {
    val result = data()
    finallyBlock()
    return result
}

```

I used some things about this try-catch example specifically to make it a bit more performant, but as a general implementation you’d simply have to use `Pair`, `Triple`, and higher-arity types like those so that you can carry _all_ the lambdas until the last function in the sequence

---

<div class="post-metadata">

**Author:** ![broot](https://avatars.discourse-cdn.com/v4/letter/b/a88e57/32.png) [@broot](https://discuss.kotlinlang.org/u/broot)\
**Post date:** [July 16, 2021, 11:41am UTC](https://discuss.kotlinlang.org/t/proposal-mixfix-function-syntax/22435/6 "2021-07-16T11:41:27Z")

</div>

Yes, I was experimenting with something like this - mostly for fun. Seems like an interesting approach for making DSLs or some crazy voodoo magic framework. It has one big issue though: we need to divide our functions/blocks into intermediate and terminal ones. Or create something like `end()` which is ugly. For example, you can’t use your above code to perform `try...catch`, but without `finally`, because it won’t return a proper value.

---

<div class="post-metadata">

**Author:** ![TrevorHackman](https://avatars.discourse-cdn.com/v4/letter/t/f05b48/32.png) [@TrevorHackman](https://discuss.kotlinlang.org/u/TrevorHackman)\
**Post date:** [July 20, 2021, 9:11pm UTC](https://discuss.kotlinlang.org/t/proposal-mixfix-function-syntax/22435/7 "2021-07-20T21:11:20Z")

</div>

@kyay10 I think that your solution, chaining high-order infix functions, is the best you can do currently, but there is a lot of overhead.

I would like to see a way to write `multi-part` functions without that overhead. For example a `trifix` function that’s like infix but with three arguments and two names. The callsite looks like `arg1 trifixFun1 arg2 trifixFun2 arg3`. The goal is to be equivalent sugar for `trifixFun(arg1, arg2, arg3)`

---

<div class="post-metadata">

**Author:** ![broot](https://avatars.discourse-cdn.com/v4/letter/b/a88e57/32.png) [@broot](https://discuss.kotlinlang.org/u/broot)\
**Post date:** [July 20, 2021, 9:41pm UTC](https://discuss.kotlinlang.org/t/proposal-mixfix-function-syntax/22435/8 "2021-07-20T21:41:44Z")

</div>

By the way, this is not the answer you expected, but I sometimes use functions that receives several functions and to me the cleanest is to write it as e.g.:

```
doSomething(
    onSuccess = {
        ...
    },
    onFailure = {
        ...
    }
)

```

In your case it could be:

```
myTry(
    block = {
        ...
    },
    myCatch = {
        ...
    },
    myFinally = {
        ...
    }
)

```

Or you can hack the code formatting a little to get this:

```
myTry({
    ...
}, myCatch = {
    ...
}, myFinally = {
    ...
})

```

I’m not a big fan of the last example, but maybe you think otherwise.

---

<div class="post-metadata">

**Author:** ![mtimmerm](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/mtimmerm/32/7160_2.png) [@mtimmerm](https://discuss.kotlinlang.org/u/mtimmerm)\
**Post date:** [July 22, 2021, 11:58am UTC](https://discuss.kotlinlang.org/t/proposal-mixfix-function-syntax/22435/9 "2021-07-22T11:58:09Z")

</div>

You can implement this particular example very efficiently today – just make `myCatch` and `myFinally` inline extension functions on a `Result` receiver. No extra objects, no lambda objects.

The only thing that’s really missing is an automatic conversion from `Result` to `Result.getOrThrow()` if `myFinally` is _not_ called.

I think that’s not so bad – you can always call `getOrThrow` directly instead of `myFinally`.

Given how well we can do already, I don’t think the language needs a special mixfix call syntax. Automatic conversions might be nice, though.

---

<div class="post-metadata">

**Author:** ![TrevorHackman](https://avatars.discourse-cdn.com/v4/letter/t/f05b48/32.png) [@TrevorHackman](https://discuss.kotlinlang.org/u/TrevorHackman)\
**Post date:** [July 22, 2021, 4:06pm UTC](https://discuss.kotlinlang.org/t/proposal-mixfix-function-syntax/22435/10 "2021-07-22T16:06:07Z")

</div>

There are extra objects and a lot of overhead. You need some intermediary that your first infix function outputs for your second infix function to work on. And if your functions are high-order functions, then you’d like to inline all of it. But you can’t achieve the same result as a single inlined function that takes many arguments with seperate functions that take only 2 arguments each.

---

<div class="post-metadata">

**Author:** ![broot](https://avatars.discourse-cdn.com/v4/letter/b/a88e57/32.png) [@broot](https://discuss.kotlinlang.org/u/broot)\
**Post date:** [July 22, 2021, 9:55pm UTC](https://discuss.kotlinlang.org/t/proposal-mixfix-function-syntax/22435/11 "2021-07-22T21:55:02Z")

</div>

Actually, you can implement this with chaining in the way that it will inline everything and it won’t create any intermediate objects\*. But it would be still suboptimal as it generates more bytecode and internally performs two `try...catch` operations instead of one.

edit: \*) Well, we would need to create an additional object in the case of an exception.
