Functional constructs for Kotlin

Overview

funKTionale

Functional constructs and patterns for Kotlin

NOTE: Development of this project is frozen, as it will eventually be made obsolete by Arrow, which merges the functionality of funKTionale and Kategory. If you are not yet using funKTionale, we recommend you start with Arrow instead.

Modules

Module Description Internal Dependencies Size(KB)
funktionale-all GOTY edition. Every other module content is included but not Experimental module N/A 1372
funktionale-collections Collections related extensions such as tail, prependTo and others N/A 4
funktionale-complement Extension functions for predicates to generate complement functions N/A 36
funktionale-composition Extensions andThen (forwardCompose) and compose for functions N/A 8
funktionale-currying Extension curried and uncurried for functions N/A 348
funktionale-either Either and Disjuntion (right-biased Either) types funktionale-option 44
funktionale-experimental Playground and examples. Not to be used on production funktionale-all 116
funktionale-memoization Memoization for functions N/A 108
funktionale-option Option type funktionale-collections and funktionale-utils 20
funktionale-pairing Transformations for functions with arity 2 or 3 to one parameter of type Pair or Triple respectively N/A 8
funktionale-partials Partial applied functions N/A 688
funktionale-pipe pipe operator N/A 36
funktionale-reverse Extension reverse for functions N/A 32
funktionale-state state monad N/A 20
funktionale-try Try computation type funktionale-either 16
funktionale-utils identity and constant functions and Partial Functions N/A 20
funktionale-validation Validation types and functions with Disjunctions funktionale-either 12

Documentation

Read the Wiki

Conference and talks

Functional Programming in Kotlin with funKTionale (video, presentation)

Maven (and Gradle)

You must configure your pom.xml file using JCenter repository

<repository>
    <id>central</id>
    <name>bintray</name>
    <url>http://jcenter.bintray.com</url>
</repository>

Then you can use any funKTionale module to your library

<dependency>
    <groupId>org.funktionale</groupId>
    <artifactId>funktionale-all</artifactId>
    <version>1.2</version>
</dependency>

How to contribute?

Rise your PR against Experimental module (funktionale-experimental). Once it gets approved I'll move it to a proper module

Comments
  • Try.onEach

    Try.onEach

    What I found missing in Try is possibility to do something on value and return it. For example:

    Try {
       // ...
    }.onEach {
       printLog(it)
    }.map {
       // ...
    }
    

    instead of

    Try {
       // ...
    }.map {
       printLog(it)
       it
    }.map {
       // ...
    }
    
    opened by nkoder 16
  • Refine generics in Option and Either

    Refine generics in Option and Either

    Description

    Better handle Option and Either generics. The default upper bounds in Kotlin, if not specified, is Any? -> [https://kotlinlang.org/docs/reference/generics.html#upper-bounds (https://kotlinlang.org/docs/reference/generics.html#upper-bounds).

    Without these changes, it is currently legal to have a nullable option value:

    fun getNull(): Option<String?> = Option.Some(null) 
    

    Examples

        class Value<out T>(val value: T) /* i.e. NullableValue<out T : Any?> */ {
            override fun hashCode(): Int = value!!.hashCode() // must account for possibly null value (!! operator)
        }
    
        class NonNullValue<out T : Any>(val value: T) {
            override fun hashCode(): Int = value.hashCode() // value is not null, no need for !!
        }
    
        @Test fun generics() {
            // Legal to use 'String?' instead of 'String'
            val nullValue: Value<String?> = Value(null)
    
            // Compile error for nullable generic type
    //        val nonNullValue: NonNullValue<String?>
    
            val nonNullValue: NonNullValue<String>
            nonNullValue = NonNullValue("non-null")
    
            assertEquals("default", nullValue.value ?: "default")
            assertEquals("non-null", nonNullValue.value ?: "default")
        }
    
    opened by laynepenney 13
  • Question regarding memoization of member functions

    Question regarding memoization of member functions

    Hi Mario,

    thank you very much for funKTionale!

    I have a question regarding memoization of member functions. I'm used to Java and Groovy and a Kotlin Newbie.

    Maybe you have some time and can give some insights on this...

    I'd like to memoize the sum member function of this immutable data class (just a silly example)

    package tryout
    
    data class MyDataClass(val a: Int = 1,
                           val b: Int = 2) {
    
        fun sum(): Int {
            println("Calculating...")
            return a + b
        }
    }
    
    fun main(args: Array<String>) {
        val myData = MyDataClass()
        println(myData.sum())
        println(myData.sum())
        println(myData.sum())
    }
    

    In groovy I can do this using an annotation

    package tryout
    
    import groovy.transform.CompileStatic
    import groovy.transform.Immutable
    import groovy.transform.Memoized
    
    @CompileStatic
    @Immutable
    class MyGroovyDataClass {
    
    	int a, b
    
    	@Memoized
    	int sum() {
    		println("Calculating...")
    		a + b
    	}
    
    	static void main(String[] args) {
    		def myData = new MyGroovyDataClass(1, 2)
    		println(myData.sum())
    		println(myData.sum())
    		println(myData.sum())
    	}
    }
    

    If I want to do this using funkTionale, then there is at the moment "only" this solution, right?

    package tryout
    
    import org.funktionale.memoization.memoize
    
    data class MyMemoizedDataClassV1(val a: Int = 1,
                                     val b: Int = 2) {
    
        private val memoizedSum: (Int, Int) -> Int = { i: Int, j: Int ->
            println("Calculating...")
            i + j
        }.memoize()
    
        fun sum(): Int {
            return memoizedSum(a, b)
        }
    }
    
    fun main(args: Array<String>) {
        val myData = MyMemoizedDataClassV1()
        println(myData.sum())
        println(myData.sum())
        println(myData.sum())
    
        val myData2 = myData.copy(b = 99)
        println(myData2.sum())
        println(myData2.sum())
        println(myData2.sum())
    
        val myData3 = myData2.copy(a = 101)
        println(myData3.sum())
        println(myData3.sum())
        println(myData3.sum())
    }
    

    Or is there a "more direct" solution?

    Thanks for your time & best regards, Peti

    opened by Petikoch 4
  • 'partially(...)' for multiple arguments functions?

    'partially(...)' for multiple arguments functions?

    Can I transform function like fun myProc(a:Int, b: String, c: Float) to fun myProc(c:Float) in one step?

    Right now I use code myProc.partially1(1).partially1("") , but maybe there are best solution?

    opened by y2k 4
  • The Either type is unbiased

    The Either type is unbiased

    Hi!

    I just wanted to clarify whether it was a design decision to make Either unbiased. As far as I remember, the only unbiased version of Either in the Scala world is ancient scala.util.Either and it's criticized by everyone left and right for exactly its unbiased nature.

    Pretty much all alternatives including scala.util.Try, scalaz.\/ or cats.data.Xor are right-biased. In your wiki you are also pointing out that

    Traditionally the Left represent an error and Right a correct return

    So, why not make it right-biased by design and provide map and flatMap? It would make it even more useful.

    Thank you for a great library!

    opened by denisftw 3
  • Hi, gradle compile maybe not work at 1.2 version

    Hi, gradle compile maybe not work at 1.2 version

    repositories {
        mavenCentral()
        jcenter()
        maven { url "https://jitpack.io" }
    }
    
    dependencies {
        compile 'org.funktionale:funktionale:1.2'
    }
    
    opened by fly7632785 2
  • Better support for coroutines

    Better support for coroutines

    Functions like eitherTry and Try would also be useful when catching exceptions thrown by suspending functions. The current implementations don't support this. For example, I cannot to this:

    fun main(args: Array<String>) = runBlocking {
        val a = async<String>(CommonPool) {
            throw Throwable()
        }
    
        val result = eitherTry {
            a.await()
        }
        println(result)
    }
    

    This fails to compile on a.await because we are not in a suspending block.

    I see two potential solutions:

    • Add new functions (or change existing signatures) to support coroutines. E.g: eitherTry becomes suspend fun <T> eitherTry(body: suspend () -> T): Either<Throwable, T>
    • Simply mark these functions inline.
    opened by okkero 2
  • Would you share the script to generate functions with multiple generic params?

    Would you share the script to generate functions with multiple generic params?

    In your talk you said you have a script to generate functions like this:

    infix inline fun <P1, R> P1.pipe(t: (P1) -> R): R = t(this)
    
    infix inline fun <P1, P2, R> P1.pipe2(crossinline t: (P1, P2) -> R): (P2) -> R = { p2 -> t(this, p2) }
    
    infix inline fun <P1, P2, P3, R> P1.pipe3(crossinline t: (P1, P2, P3) -> R): (P2, P3) -> R = { p2, p3 -> t(this, p2, p3) }
    

    Would you mind sharing it?

    I want to automate the generation of functions like that.

    opened by vjames19 2
  • Rename second argument in Option.fold

    Rename second argument in Option.fold

    The name of the second argument "f" like a not very good solution. I like to use named argument for fold calling and any more functions. Of course, I can write:

     fold(isEmpty = {...}){value -> ...}
    

    But I want to be able to write like this

     fold(isEmpty = {...},  some = {value -> ...})
    
    opened by georgeci 2
  • Licensing

    Licensing

    I'd like to use this library in an application of mine. Would you be willing to add an open source license like Apache or MIT to the project? I could create a pull request to do it if you'd like.

    opened by jeffcharles 2
  • DEXOPT error on Android 4.2 and older

    DEXOPT error on Android 4.2 and older

    Hi,

    when using this library on Android 4.2 and older, I get an INSTALL_FAILED_DEXOPT. It might have something to do with this problem: http://stackoverflow.com/questions/21434837/installing-kotlin-android-project-fails-with-install-failed-dexopt After recompiling funKTionale with latest Kotlin (Beta 2), everything works fine. Could you please upload a recompiled version to the official maven repo? Many thanks.

    opened by daemontus 2
  • Bintray decommisioning means v1.2 is unavailable from a maven repo

    Bintray decommisioning means v1.2 is unavailable from a maven repo

    I was able to build v1.2 and publish to my local nexus repo, but it might be useful for you to publish to mavenCentral or another publicly available repo and update the mavenCentral.com details for the module.

    opened by alexis-airwallex 1
  • Replaced by Arrow?

    Replaced by Arrow?

    It sounds from https://www.47deg.com/blog/announcing-arrow-for-kotlin/ like this project has been replaced by Arrow—if that's true, could you add a note to that effect to the top of the readme?

    opened by timmc-bcov 1
  • Include only org.funktionale.* in fat jar for funktionale-all package (Fixes #42)

    Include only org.funktionale.* in fat jar for funktionale-all package (Fixes #42)

    This is an attempt to fix #42.

    Instead of adding more excludes to remove unwanted libraries (JetBrains annotations and IntelliJ annotations), I've specified that only the contents of the org.funktionale package should be included in it - this is easier than having to maintain a list of excluded libraries, even if development has now halted in favor of Arrow.

    I couldn't figure out how to build the project locally, but I hope this solution works.

    opened by zsmb13 1
  • Android Gradle 3.0: Multiple dex files define Lorg/jetbrains/annotations/TestOnly

    Android Gradle 3.0: Multiple dex files define Lorg/jetbrains/annotations/TestOnly

    I figured that in my compilation problem with gradle 3.0 described here [1] the reason is in fact funktionale. I cannot pinpoint it any further but I suppose it's a good idea to report it here. It used to compile just fine before I updated my build environment.

    [1] https://stackoverflow.com/questions/48504912/android-gradle-3-0-multiple-dex-files-define-lorg-jetbrains-annotations-testonl

    opened by kar 1
  • Functions like Try.flatMap or fold swallow RuntimeExceptions

    Functions like Try.flatMap or fold swallow RuntimeExceptions

    Functions like Try<T>.flatMap and Try<T>.fold swallow RuntimeExceptions, making it harder to find bugs.

    For example, I tried to use a TODO(), but my application did not terminate:

    fun main(args: Array<String>) {
        val result = Success("Test").flatMap<Unit> { TODO() }
        println(result)
    }
    

    Instead, the console prints

    Failure(kotlin.NotImplementedError: An operation is not implemented.)

    opened by nhaarman 0
Releases(1.2)
  • 1.2(Nov 29, 2017)

    New

    • Compiled with Kotlin 1.2 Fixed issues
    • https://github.com/MarioAriasC/funKTionale/issues/24
    • https://github.com/MarioAriasC/funKTionale/issues/27
    • https://github.com/MarioAriasC/funKTionale/issues/37
    Source code(tar.gz)
    Source code(zip)
  • 1.1(Jun 3, 2017)

  • 1.0.1(Apr 9, 2017)

  • 1.0.0-final(Feb 13, 2017)

    After one month and a half testing 1.0.0-beta I'm pleased to announce 1.0.0-final.

    There is no changes between 1.0.0-beta and 1.0.0-final apart from some changes on README.md

    Source code(tar.gz)
    Source code(zip)
  • 1.0.0-beta(Dec 30, 2016)

    WARNING: This release breaks several things from the previous releases

    • Now the library is split in several sub-modules. That allows you to use the features that you need (e.g. Option and Either but not Partial applied functions). If you still want to use all modules you could use the funktionale-all artifact
    • All deprecated functions are deleted
    • Option's functions toEitherLeft, toDisjunctionLeft, toEitherRight and toDisjunctionRight now are extension functions inside org.funktionale.either package inside funktionale-either module
    • eitherTry and disjunctionTry now returns Either<Throwable,T> and Disjunction<Throwable, T> respectively
    • PartialFunction now throws IllegalArgumentException if parameter doesn't pass isDefinedAt(). It reduce the amount of code need it to write partial functions
    • Partial function is now in org.funktionale.utils package inside funktionale-utils module
    • A new Try computation type in funktionale-try module
    Source code(tar.gz)
    Source code(zip)
  • 0.9.7(Dec 7, 2016)

    • Reworked Option, Either and Disjunction generics
    • desctructured() extension function for List<T> that returns a pair with head and tail inside
    • Easy to use functions on Either and Disjunction companion objects to create instances
    Source code(tar.gz)
    Source code(zip)
  • 0.9.6(Nov 23, 2016)

    • Partial Function (different to Partial applied functions)
    • Memoization improved performance
    • memoize() for () -> R
    • partially1() (a.k.a bind()) for (P1) -> R
    • paired()and unpaired() to transform between (P1, P2) -> R to (Pair<P1, P2>) -> R and backwards
    • tripled()and untripled() to transform between (P1, P2, P3) -> R to (Triple<P1, P2, P3>) -> R and backwards
    • validate() functions
    Source code(tar.gz)
    Source code(zip)
  • 0.9.5(Sep 26, 2016)

  • 0.9(Aug 7, 2016)

    • Disjunction (Right-Biased Either)
    • Optimized options (ht: https://github.com/mustafin)
    • Validation (ht https://github.com/loicdescotte)

    Next mayor release (1.0) Will delete every deprecated method and will come in modules/jars for easier use. E.g: a funktionale-all.jar, funktionale-option.jar and so on

    Source code(tar.gz)
    Source code(zip)
  • 0.8(Feb 15, 2016)

  • 0.7(Feb 13, 2016)

  • 0.6.1_1.0.0-rc(Feb 5, 2016)

  • 0.6_1.0.0-beta-3594(Dec 7, 2015)

  • 0.6_1.0.0-beta(Oct 22, 2015)

  • M14(Oct 1, 2015)

  • 0.6_M13(Sep 16, 2015)

  • 0.6_M12(Aug 1, 2015)

    • tail() and prependTo() for List
    package org.funktionale.collections
    
    import org.testng.Assert
    import org.testng.annotations.Test
    
    
    public class CollectionsTest {
        @Test fun tail() {
            Assert.assertEquals(listOf(1, 2, 3).tail(), listOf(2, 3))
        }
    
        @Test fun prependTo() {
            Assert.assertEquals(1 prependTo listOf(2, 3), listOf(1, 2, 3))
        }
    }
    
    • new operations for Option and Either

    Breaking changes

    • Now forEach() in both RightProjection and LeftProjection return Unit
    • toString(), hashcode() and equals() are now properly implemented for Right and Left
    • either was renamed to eitherTry
    Source code(tar.gz)
    Source code(zip)
  • 0.5.1.1_M12(Jun 11, 2015)

  • 0.5.1_M12(May 29, 2015)

  • 0.5_M11(May 25, 2015)

Owner
Mario Arias
Mario Arias
A functional, fractional-byte programming language

Fig A functional, fractional-byte programming language. Tired of annoying Unicode codepages in your favorite golfing languages? Fig uses pure, printab

null 10 Dec 15, 2022
Sample Ktor app using a functional stack

samstack This is a template project you can clone and use as a basis for your own Kotlin based microservices. This application structure is my persona

Sam 6 Nov 16, 2022
Sample Ktor app using a functional stack

samstack This is a template project you can clone and use as a basis for your own Kotlin based microservices. This application structure is my persona

Sam 18 Jul 21, 2022
Repo: Programming problems with solutions in Kotlin to help avid Kotlin learners to get a strong hold on Kotlin programming.

Kotlin_practice_problems Repo: Programming problems with solutions in Kotlin to help avid Kotlin learners to get a strong hold on Kotlin programming.

Aman 0 Oct 14, 2021
Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP)

Mockative Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP). Installation Mockative uses KSP to generate

Mockative 121 Dec 26, 2022
Kotlin-oop - Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura.

Projeto React OOP Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura

Marcos Felipe 1 Jan 5, 2022
Kotlin-koans - Kotlin Koans are a series of exercises to get you familiar with the Kotlin Syntax

kotlin-koans-edu Kotlin Koans are a series of exercises to get you familiar with

null 1 Jan 11, 2022
Kotlin TodoMVC – full-stack Kotlin application demo

Kotlin full stack TodoMVC This project is an example implementation of the TodoMVC app written in Kotlin. More specifically, it's the Kotlin port of t

Gyula Voros 22 Oct 3, 2022
Integration Testing Kotlin Multiplatform Kata for Kotlin Developers. The main goal is to practice integration testing using Ktor and Ktor Client Mock

This kata is a Kotlin multiplatform version of the kata KataTODOApiClientKotlin of Karumi. We are here to practice integration testing using HTTP stub

Jorge Sánchez Fernández 29 Oct 3, 2022
Small kotlin library for persisting _single instances_ of kotlin data classes

PerSista Small library for persisting single instances of kotlin data classes. NB: PerSista uses typeOf() internally which is marked as @ExperimentalS

Eric Donovan 5 Nov 13, 2022
Kotlin Leaning Notes from Udacity Course | Kotlin Bootcamp for Programmers by Google

Kotlin Beginners Notes These are all personal notes taken from the Udacity Course (ud9011) of Kotlin Bootcamp for Programmers by Google as well as oth

Süha Tanrıverdi 34 Dec 10, 2022
Saga pattern implementation in Kotlin build in top of Kotlin's Coroutines.

Module Saga Website can be found here Add in build.gradle.kts repositories { mavenCentral() } dependencies { implementation("io.github.nomisr

Simon Vergauwen 50 Dec 30, 2022
Kotlin microservices with REST, and gRPC using BFF pattern. This repository contains backend services. Everything is dockerized and ready to "Go" actually "Kotlin" :-)

Microservices Kotlin gRPC Deployed in EC2, Check it out! This repo contains microservices written in Kotlin with BFF pattern for performing CRUD opera

Oguzhan 18 Apr 21, 2022
A sample skeleton backend app built using Spring Boot kotlin, Expedia Kotlin Graphql, Reactive Web that can be deployed to Google App Engine Flexible environmennt

spring-kotlin-gql-gae This is a sample skeleton of a backend app that was built using: Spring Boot(Kotlin) Reactive Web Sprinng Data R2DBC with MYSQL

Dario Mungoi 7 Sep 17, 2022
Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin Gradle DSL.

SampleCompose Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin

Mohammadali Rezaei 7 Nov 28, 2022
Learn-kotlin - Learning more about Kotlin in various content

Kotlin study roadmap https://kotlinlang.org/docs/reference/ Getting Started Basi

Danilo Silva 0 Jan 7, 2022
Mis experimentos con Kotlin para JetBrains Academy, certificación de Kotlin donde voy resolviendo proyectos de evaluación y haciendo actividades de cada tema.

Kotlin Academy Mis experimentos con Kotlin para JetBrains donde voy resolviendo proyectos de evaluación y haciendo actividades de cada tema. Acerca de

José Luis González Sánchez 1 Jan 10, 2022
Repositório criado para ser utilizado pelo projeto de Kotlin Collections desenvolvido em Kotlin nas aulas feitas através da plataforma Alura.

Projeto Kotlin Collections Repositório criado para ser utilizado pelo projeto de Kotlin Collections desenvolvido em Kotlin nas aulas feitas através da

Marcos Felipe 1 Jan 17, 2022
Kotlin-GraphQL-Apollo - Sencillo cliente para consumir una API GraphQL con Apollo usando Kotlin

Kotlin GraphQL Apollo Sencillo cliente para consumir una API GraphQL con Apollo

José Luis González Sánchez 2 Jan 25, 2022