Looks like a false “no argument” error with case class constructor

I have a case class that has several parameters for its constructor, and I define a companion class object that defines an alternative constructor that takes a different set of arguments, for example:

case class MyClass (c: Char, mc: List[MyClass]) object MyClass { def apply(c: Char, mc: MyClass): MyClass = { MyClass(c, List(mc)) } } 

I want to use the original case class constructor in foldRight :

 object SomeStuff { def problem (s: String) { assert(!s.isEmpty) val zero = MyClass('a', Nil) val mc2 = "Pillsy Pillsy Pillsy" foldRight(zero) { MyClass(_, List(_)) } } } 

When I do this, I get an error message from the compiler: "MyClass does not accept parameters." If I comment on the section val mc2 = ... , this problem will disappear, but MyClass explicitly accepts parameters in the definition of zero . I feel that I must be missing something really basic, but I have no idea what it is. I tried a couple of workarounds, such as defining a helper method or a function value to use as the second argument to foldRight , but none of this helps, which is not surprising, since I basically foldRight randomly.

+6
source share
1 answer

First, foldRight takes two arguments, so you cannot use operator notation (in its current form), but you can:

 ("foo" foldRight zero) { ... } 

or alternatively

 ("foo" :\ zero) { ... } 

Secondly, { MyClass(_, List(_)) } will be desugar in

 { x => MyClass(x, y => List(y)) } 

therefore, you must specify the arguments and use the new keyword to ensure that the constructor is called instead of the apply method:

 "Pillsy Pillsy Pillsy".foldRight(zero) { (c, mc) => new MyClass(c, List(mc)) } 

or use the optional apply method if you want to use underscores:

 "Pillsy Pillsy Pillsy".foldRight(zero) { MyClass(_, _) } 
+5
source

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


All Articles