Search code examples
kotlinarrow-kt

How to use arrow's type classes?


I'm trying to get familiar with the arrow-kt library, but I'm to dumb to get the easiest thing done: Using one of the built in type classes, namely 'Show' I tried it with kapt using the @extension annotation and kapt itself is generating the necessary code as expected, but the reference to the extension function 'show(): String' is missing. Could somebody please help me with this problem? I wasted two days getting this to work.

Thank you very much!

Best regards

Alex

The class to be extended:

package org.hudelundpfusch.sqwakkel.arrowtest

import arrow.extension
import arrow.typeclasses.Show

class Fump(private val fumpel: String) {

    companion object {}

    override fun toString(): String {
        return "Fump(fumpel='$fumpel')"
    }

}

@extension
interface FumpShow
    : Show<Fump> {
    override fun Fump.show(): String = toString()
}

Here I wanted to use the extension function:

package org.hudelundpfusch.sqwakkel.arrowtest

class Gump {

    private val fump: Fump = Fump("Fumpel!")

    fun gumpel(): String = fump.show()

}

But the reference to 'fump.show()' is missing =(


Solution

  • You're missing show.run { }. For extension functions defined in interfaces to work you need to be on their scope, using run or making a class where you're using it extend it. Either

    class Gump: FumpShow
    

    or

    Fump.show().run { fump.show() }
    

    should give you the results that you want.

    Another option would be importing the show function Arrow Meta's processor would create for you using @extension. Make sure to have it properly configured in your build.gradle

    kapt "io.arrow-kt:arrow-meta:$arrow_version"
    

    and then it should be as easy as importing show from IntelliJ's suggestions.