Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent behaviour when using companion object as argument to function accepting block #5570

Closed
scabug opened this issue Mar 14, 2012 · 3 comments

Comments

@scabug
Copy link

scabug commented Mar 14, 2012

I spotted some possibly inconsistent behaviour when passing companion objects as the shorthand parameter to functions accepting a block, such as map, compared to when passing the automatically created companion object of a case class. StackOverflow question can be found here.

Basically, it works when the class is a case class, but not if it's not, and the companion object is manually defined.

For example

class Model
class ModelWrapper(val m: Model)
object ModelWrapper { def apply(model: Model) = new ModelWrapper(model) }

val m1 = new Model; val m2 = new Model; val m3 = new Model

List(m1, m2, m3).map(ModelWrapper)

<console>:14: error: type mismatch;
 found   : ModelWrapper.type (with underlying type object ModelWrapper)
 required: Model => ?
                  List(m1, m2, m3).map(ModelWrapper)

//however List(m1, m2, m3).map(ModelWrapper.apply) and List(m1, m2, m3).map(ModelWrapper.(_)) both work

Whereas with a case class there's no problem

class Model
case class ModelWrapper(model: Model) 

val m1 = new Model; val m2 = new Model; val m3 = new Model

List(m1, m2, m3).map(ModelWrapper)

Serj on SO posted a workaround - making the companion object extend Function[Model, ModelWrapper]. However, according to the Scala specification, as far as I can see, the built-in companion object doesn't extend Function - should this difference in behaviour exist?

@scabug
Copy link
Author

scabug commented Mar 14, 2012

Imported From: https://issues.scala-lang.org/browse/SI-5570?orig=1
Reporter: Russell Dunphy (tetristic)
Affected Versions: 2.9.0-1
Duplicates #3664

@scabug
Copy link
Author

scabug commented Mar 16, 2012

@paulp said:
The behavior is expected. That the companion extends FunctionN should be added to the spec; I also think we could/should eta-expand naked applies. This was discussed at some point, I forget the resolution if any.

@scabug
Copy link
Author

scabug commented Mar 27, 2012

@adriaanm said:
originally case classes gave rise to factory methods, then we switched to companion objects with an apply (and an unapply, which triggered the move to companion objects); to keep backwards compatibility, we consider case class companion objects as functions (but not others)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants