Using constructor where function expected

╄→尐↘猪︶ㄣ 提交于 2019-12-13 12:59:16

问题


Having two simple classes taking Int as an argument:

case class Foo(i: Int)
     class Bar(j: Int)

I can say:

List(1,2,3) map Foo

Which works fine and is equivalent to a bit more verbose:

List(1,2,3) map {Foo(_)}

However Bar (because it is not a case class?) cannot be used in the same construct:

List(1,2,3) map Bar

  error: not found: value Bar
          List(1,2,3) map Bar
                          ^

Is there some special syntax to reference any constructor and take advantage of eta expansion? List(1,2,3) map {new Bar(_)} seems a bit more verbose compared to Foo.


回答1:


It works in the former case, because companion object of a case class extends appropriate FunctionN trait. (object Foo extends (Int => Foo) in your example.) For non-case classes, you could do this manually:

scala> class Bar(i: Int)
defined class Bar

scala> class Bar(i: Int); object Bar extends (Int => Bar) { def apply(i: Int) = new Bar(i) }
defined class Bar
defined module Bar

scala> List(2, 3) map Bar
res17: List[Bar] = List(Bar@1f99e90, Bar@1191056)

IMO it's better to go with new Bar(_) as this extra boilerplate might not be worth the little concision achieved.




回答2:


Since Foo is a case class there is also a companion object called Foo, which implements the Function1 interface (had the constructor taken three arguments it would have been the Function3 interface).



来源:https://stackoverflow.com/questions/7695515/using-constructor-where-function-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!