Why do case class companion objects extend FunctionN?

前端 未结 4 1888
陌清茗
陌清茗 2020-12-05 02:04

When you create a case class, the compiler creates a corresponding companion object with a few of the case class goodies: an apply factory method matching the p

4条回答
  •  鱼传尺愫
    2020-12-05 02:49

    Aside from oxbow_lakes's reply about the naturalness of it, it can often be useful to have constructors available as first-class functions, particularly in conjunction with Scala collections higher-order functions. For (a trivial) example,

    scala> case class Foo(i : Int)
    defined class Foo
    
    scala> List(1, 2, 3) map Foo   
    res0: List[Foo] = List(Foo(1), Foo(2), Foo(3))
    

提交回复
热议问题