面向对象的编程和函数式编程基本相同的证据 - vavr


在静态类型语言的上下文中,两种范例在技术上都使用更高阶函数和对象封装。类型用于建模领域,构建器是帮助创建实例的上下文。代码如下:

/*
 * Search and destroy 
 */


interface Ant {
   
// properties omitted
}

@FunctionalInterface
interface Poison {
    Ant apply(Ant ant);
}

final class Search {

   
// omitted private constructors and instance vars

    static Search of(Criteria criteria) {
        return ...;
    }

    Ant destroy(Poison poison) {
        return poison.apply(ant);
    }
}

使用调用代码:

Ant ant = Search.of(antCriteria).destroy(poison);