代码之家  ›  专栏  ›  技术社区  ›  WeiChing 林煒æ¸

为什么scala cats使用类型类而不是继承?

  •  3
  • WeiChing æž—ç…’æ¸  · 技术社区  · 6 年前

    在继承上使用typeclass有什么意义?

    Monad

    def f[A : Monad](x:A) = ??? 
    

    def f[A <: Monad](x:A) = ???  
    f(x) // where x is a CatsList which implements Monad trait.
    

    2 回复  |  直到 6 年前
        1
  •  4
  •   Brian McCutchon    6 年前

    Measurable Functor

    trait Measurable {
      def length: Int
    }
    
    trait Functor[A] {
      def map[B](f: A => B): Functor[B]
    }
    

    class ListIsMeasurable(ls: List[_]) extends Measurable {
      def length = ls.length
    }
    

    def foo(x: Measurable with Functor) = ???
    

    List Measurable with Functor n 2^n

    def foo[A : Measurable : Functor](a: A) = ???
    
        2
  •  4
  •   Brian McCutchon    6 年前

    Monoid

    trait Monoid[A] {
      def empty: A
      def combine(x: A, y: A): A
    }
    

    empty

    现在让我们定义一个 幺半群 为了一些像 Tuple2 :

    implicit def tupleMonoid[A: Monoid, B: Monoid]: Monoid[(A, B)] = ...
    

    现在你在一个继承权根本不能让你得到任何东西的地方。通过类型类,我们可以向类型类实例添加条件。也就是说,元组是 幺半群 ,当它的两种类型都是 幺半群 有了继承权,你就不能这样做。