Declaring a class constructor ... Two ways to declare the same object?

I would like to explain the difference, for example, between this declaration:

class Clazz(param1: String, param2: Integer) 

and this one:

 class Clazz(param1: String)(param2: Integer) 

The second declaration only affects the way objects are created, or is there a deeper reason that I don’t know about.

One of the reasons I thought would be a few variable-length parameters, for example:

 class Clazz(param1: String*)(param2: Integer*) 

So are there any others?

+6
source share
2 answers

# 1 Enter the output. It goes from left to right and runs for each parameter list.

 scala> class Foo[A](x: A, y: A => Unit) defined class Foo scala> new Foo(2, x => println(x)) <console>:24: error: missing parameter type new Foo(2, x => println(x)) ^ scala> class Foo[A](x: A)(y: A => Unit) defined class Foo scala> new Foo(2)(x => println(x)) res22: Foo[Int] = Foo@4dc1e4 

# 2 List of implicit parameters.

 scala> class Foo[A](x: A)(implicit ord: scala.Ordering[A]) { | def compare(y: A) = ord.compare(x, y) | } defined class Foo scala> new Foo(3) res23: Foo[Int] = Foo@965701 scala> res23 compare 7 res24: Int = -1 scala> new Foo(new {}) <console>:24: error: No implicit Ordering defined for java.lang.Object. new Foo(new {}) ^ 
+11
source

In the second version, you declare the primary curries constructor for Clazz. Thus, the difference between the two versions is the same as the difference between the "normal" and curry functions in Scala, i.e.

 def foo(param1: String, param2: Int) def foo(param1: String)(param2: Int) 

In most cases, both declarations can be used interchangeably, but if you often have to perform the curry function, then it makes sense to declare it in curry. Note that you can also convert a normal function or even a constructor to curry, for example, you can convert your regular Clazz constructor to curry using this:

 (new Clazz(_, _)).curried 

You also need several parameter lists if you pass an implicit value (since the implicit keyword applies to the complete parameter list)

+3
source

Source: https://habr.com/ru/post/908600/


All Articles