开发者

Using constructor where function expected

开发者 https://www.devze.com 2023-04-12 03:19 出处:网络
Having two simple classes taking Int as an a开发者_JAVA技巧rgument: case class Foo(i: Int) class Bar(j: Int)

Having two simple classes taking Int as an a开发者_JAVA技巧rgument:

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.


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.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消