Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using constructor where function expected

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.

like image 590
Tomasz Nurkiewicz Avatar asked Oct 08 '11 07:10

Tomasz Nurkiewicz


People also ask

How do you define a function in a constructor?

The function statement is not the only way to define a new function; you can define your function dynamically using Function() constructor along with the new operator. Note − Constructor is a terminology from Object Oriented Programming.

Is it possible to use function constructor to create a new function in JS?

The Function() constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as eval() .

How do you assign a function to a variable with a JavaScript constructor?

// using constructor function function Person () { this.name = 'Sam' } let person1 = new Person(); let person2 = new Person(); // adding new property to person1 person1.

How do we invoke a constructor function?

Constructors are invoked automatically when we create objects. Constructors should be declared in the public section of the Class. Constructors cannot return values to the calling program because they do not have return types. Constructors should always be non-virtual.


1 Answers

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.

like image 107
missingfaktor Avatar answered Sep 21 '22 02:09

missingfaktor