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
.
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.
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() .
// using constructor function function Person () { this.name = 'Sam' } let person1 = new Person(); let person2 = new Person(); // adding new property to person1 person1.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With