Scala compilation error - scala

Can't figure out what's wrong with StrangeIntQueue extending Queue, why there is an error "Not enough arguments for constructor Queue: (leading: Int)list.Lister.Queue[Int]. Unspecified value parameter leading". How can I specify it?
class Queue[+T](
private val leading: T
) {
def enqueue[U >: T](x: U) =
new Queue[U](leading: U) // ...
}
class StrangeIntQueue(private val leading: Int) extends Queue[Int] {
override def enqueue(x: Int) = {
println(math.sqrt(x))
super.enqueue(x)
}
}

extends Queue[Int](leading)
You have to pass on the arguments even if it seems "obvious" what to do.
Note also that since you have declared leading private, you'll actually get two copies: one for StrangeIntQueue and one for Queue. (Otherwise you could have just StrangeIntQueue(leading0: Int) extends Queue[Int](leading0) and use the inherited copy of leading inside.)

The primary constructor of class Queue, which StrangeIntQueue extends, takes a parameter, but you're not passing it anything for the parameter. Try this:
class StrangeIntQueue(leading: Int) extends Queue[Int](leading) {
// ...
}

Related

Correct method signature for RichGroupReduceFunction?

The below extended class of RichGroupReduceFunction, does not compile. The signature seemingly does not match the interface. I can't tell the difference.
class SPointReduce extends RichGroupReduceFunction[Int, Int] {
override def reduce (
values: Iterable[Int],
out: Collector[Int]): Unit = {
values.foreach {
value: Int =>
out.collect(value)
}
}
}
The compiler reports:
Error:(62, 16) method reduce overrides nothing.
Note: the super classes of class SPointReduce contain the
following, non final members named reduce: def reduce(x$1:
Iterable[Nothing],x$2: org.apache.flink.util.Collector[Nothing]): Unit
override def reduce (
You have to make sure that you import the java.lang.Iterable when you override the reduce method of RichGroupReduceFunction. Otherwise, you will get the above mentioned error.

Extend generic type - PriorityQueue

I can't understand why I need () and hence where MyTypeQueOrdering goes.
Here is header of PriorityQueue, found on official github:
class PriorityQueue[A](implicit val ord: Ordering[A])
Here is my try (which works):
class MyType{
}
object MyTypeQueOrdering extends Ordering[MyType]{
def compare (n1:MyType, n2:MyType) = -1
}
class MyTypeQue extends PriorityQueue[MyType]()(MyTypeQueOrdering){
}
... but I can't figure out why I need (). Does PriorityQueue[MyType]() return something?
Try making MyTypeQueOrdering an implicit object:
object Implicits {
//implicit objects can't be top-level ones
implicit object MyTypeQueOrdering extends Ordering[MyType] {
def compare(n1: MyType, n2: MyType) = -1
}
}
This way you can omit both parentheses:
import Implicits._
class MyTypeQue extends PriorityQueue[MyType] { ... }
The reason you need the empty parentheses in your example is because PriorityQueue[MyType](MyTypeQueOrdering) would assume you're trying to pass the ordering as a constructor parameter. So that's why you need to explicitly show no-arg instantiation and then passing the ordering

Accessibility of primary constructor parameters in scala

I am having hard time to understand the concept of primary constructor and it's parameters. What I have understood till now is: if we define a class as following
class Example(a: Int, b: Int)
Scala compiler generates a primary constructor of the class Examples with the above two parameters. But, it doesn't defines fields a and b in the class Example's definition. But if we define
class Example(val a: Int, val b: Int)
scala compiler generates the primary constructor as above and adds two fields in the class definition.
Now the problem comes when I am trying an example like
class PrimaryConstructor(a: Int, b: Int){
override def toString() = "PrimaryConstructor(" + this.a + ", " + this.b + ")"
}
The above code compiles well even if there is no fields named either a or b. I am not able to understand that if there are no any fields as such then how I am able to access them using this: the current object reference.
object Main{
def main(args: Array[String]){
val primaryConstructor = new PrimaryConstructor(1, 2)
println(primaryConstructor.a)
}
}
While if I try to access them from out side the class definition as above, I get the following error message after compilation.
error: value a is not a member of PrimaryConstructor
println(primaryConstructor.a)
I can understand this. But, how can I access those fields using this? Please help me to understand this.
It basically generates a private val, so
class A(a:Int) {
def func = a
}
and
class A(private[this] val a:Int) {
def func = a
}
are equivalent. This may not be entirely true if you omit the function.
When a constructor parameter is referred outside the constructor body ( such as in example func above ), Scala generates a private[this] val, otherwise not.
You can check scala spec for more details or look at this stackoverflow question
Martin's answer is great:
It basically generates a private val, so
class A(a:Int) {
def func = a
}
and
class A(private[this] val a:Int) {
def func = a
}
are equivalent and you can access a from inside your class.
But, note that class A(a: Int) means that the field a is instance private. Meaning that you cannot write something like this:
class A(a: Int){
def sum(other: A): Int = {
this.a + other.a
}
}
other.a is not allowed even though both instances are of the same type. You can only use this.a.

How to override apply in a case class companion

So here's the situation. I want to define a case class like so:
case class A(val s: String)
and I want to define an object to ensure that when I create instances of the class, the value for 's' is always uppercase, like so:
object A {
def apply(s: String) = new A(s.toUpperCase)
}
However, this doesn't work since Scala is complaining that the apply(s: String) method is defined twice. I understand that the case class syntax will automatically define it for me, but isn't there another way I can achieve this? I'd like to stick with the case class since I want to use it for pattern matching.
The reason for the conflict is that the case class provides the exact same apply() method (same signature).
First of all I would like to suggest you use require:
case class A(s: String) {
require(! s.toCharArray.exists( _.isLower ), "Bad string: "+ s)
}
This will throw an Exception if the user tries to create an instance where s includes lower case chars. This is a good use of case classes, since what you put into the constructor also is what you get out when you use pattern matching (match).
If this is not what you want, then I would make the constructor private and force the users to only use the apply method:
class A private (val s: String) {
}
object A {
def apply(s: String): A = new A(s.toUpperCase)
}
As you see, A is no longer a case class. I am not sure if case classes with immutable fields are meant for modification of the incoming values, since the name "case class" implies it should be possible to extract the (unmodified) constructor arguments using match.
UPDATE 2016/02/25:
While the answer I wrote below remains sufficient, it's worth also referencing another related answer to this regarding the case class's companion object. Namely, how does one exactly reproduce the compiler generated implicit companion object which occurs when one only defines the case class itself. For me, it turned out to be counter intuitive.
Summary:
You can alter the value of a case class parameter before it is stored in the case class pretty simply while it still remaining a valid(ated) ADT (Abstract Data Type). While the solution was relatively simple, discovering the details was quite a bit more challenging.
Details:
If you want to ensure only valid instances of your case class can ever be instantiated which is an essential assumption behind an ADT (Abstract Data Type), there are a number of things you must do.
For example, a compiler generated copy method is provided by default on a case class. So, even if you were very careful to ensure only instances were created via the explicit companion object's apply method which guaranteed they could only ever contain upper case values, the following code would produce a case class instance with a lower case value:
val a1 = A("Hi There") //contains "HI THERE"
val a2 = a1.copy(s = "gotcha") //contains "gotcha"
Additionally, case classes implement java.io.Serializable. This means that your careful strategy to only have upper case instances can be subverted with a simple text editor and deserialization.
So, for all the various ways your case class can be used (benevolently and/or malevolently), here are the actions you must take:
For your explicit companion object:
Create it using exactly the same name as your case class
This has access to the case class's private parts
Create an apply method with exactly the same signature as the primary constructor for your case class
This will successfully compile once step 2.1 is completed
Provide an implementation obtaining an instance of the case class using the new operator and providing an empty implementation {}
This will now instantiate the case class strictly on your terms
The empty implementation {} must be provided because the case class is declared abstract (see step 2.1)
For your case class:
Declare it abstract
Prevents the Scala compiler from generating an apply method in the companion object which is what was causing the "method is defined twice..." compilation error (step 1.2 above)
Mark the primary constructor as private[A]
The primary constructor is now only available to the case class itself and to its companion object (the one we defined above in step 1.1)
Create a readResolve method
Provide an implementation using the apply method (step 1.2 above)
Create a copy method
Define it to have exactly the same signature as the case class's primary constructor
For each parameter, add a default value using the same parameter name (ex: s: String = s)
Provide an implementation using the apply method (step 1.2 below)
Here's your code modified with the above actions:
object A {
def apply(s: String, i: Int): A =
new A(s.toUpperCase, i) {} //abstract class implementation intentionally empty
}
abstract case class A private[A] (s: String, i: Int) {
private def readResolve(): Object = //to ensure validation and possible singleton-ness, must override readResolve to use explicit companion object apply method
A.apply(s, i)
def copy(s: String = s, i: Int = i): A =
A.apply(s, i)
}
And here's your code after implementing the require (suggested in the #ollekullberg answer) and also identifying the ideal place to put any sort of caching:
object A {
def apply(s: String, i: Int): A = {
require(s.forall(_.isUpper), s"Bad String: $s")
//TODO: Insert normal instance caching mechanism here
new A(s, i) {} //abstract class implementation intentionally empty
}
}
abstract case class A private[A] (s: String, i: Int) {
private def readResolve(): Object = //to ensure validation and possible singleton-ness, must override readResolve to use explicit companion object apply method
A.apply(s, i)
def copy(s: String = s, i: Int = i): A =
A.apply(s, i)
}
And this version is more secure/robust if this code will be used via Java interop (hides the case class as an implementation and creates a final class which prevents derivations):
object A {
private[A] abstract case class AImpl private[A] (s: String, i: Int)
def apply(s: String, i: Int): A = {
require(s.forall(_.isUpper), s"Bad String: $s")
//TODO: Insert normal instance caching mechanism here
new A(s, i)
}
}
final class A private[A] (s: String, i: Int) extends A.AImpl(s, i) {
private def readResolve(): Object = //to ensure validation and possible singleton-ness, must override readResolve to use explicit companion object apply method
A.apply(s, i)
def copy(s: String = s, i: Int = i): A =
A.apply(s, i)
}
While this directly answers your question, there are even more ways to expand this pathway around case classes beyond instance caching. For my own project needs, I have created an even more expansive solution which I have documented on CodeReview (a StackOverflow sister site). If you end up looking it over, using or leveraging my solution, please consider leaving me feedback, suggestions or questions and within reason, I will do my best to respond within a day.
I don't know how to override the apply method in the companion object (if that is even possible) but you could also use a special type for upper case strings:
class UpperCaseString(s: String) extends Proxy {
val self: String = s.toUpperCase
}
implicit def stringToUpperCaseString(s: String) = new UpperCaseString(s)
implicit def upperCaseStringToString(s: UpperCaseString) = s.self
case class A(val s: UpperCaseString)
println(A("hello"))
The above code outputs:
A(HELLO)
You should also have a look at this question and it's answers: Scala: is it possible to override default case class constructor?
For the people reading this after April 2017: As of Scala 2.12.2+, Scala allows overriding apply and unapply by default. You can get this behavior by giving -Xsource:2.12 option to the compiler on Scala 2.11.11+ as well.
It works with var variables:
case class A(var s: String) {
// Conversion
s = s.toUpperCase
}
This practice is apparently encouraged in case classes instead of defining another constructor. See here.. When copying an object, you also keep the same modifications.
Another idea while keeping case class and having no implicit defs or another constructor is to make the signature of apply slightly different but from a user perspective the same.
Somewhere I have seen the implicit trick, but canĀ“t remember/find which implicit argument it was, so I chose Boolean here. If someone can help me out and finish the trick...
object A {
def apply(s: String)(implicit ev: Boolean) = new A(s.toLowerCase)
}
case class A(s: String)
I faced the same problem and this solution is ok for me:
sealed trait A {
def s:String
}
object A {
private case class AImpl(s:String)
def apply(s:String):A = AImpl(s.toUpperCase)
}
And, if any method is needed, just define it in the trait and override it in the case class.
If you're stuck with older scala where you cant override by default or you dont want to add the compiler flag as #mehmet-emre showed, and you require a case class, you can do the following:
case class A(private val _s: String) {
val s = _s.toUpperCase
}
As of 2020 on Scala 2.13, the above scenario of overriding a case class apply method with same signature works totally fine.
case class A(val s: String)
object A {
def apply(s: String) = new A(s.toUpperCase)
}
the above snippet compiles and runs just fine in Scala 2.13 both in REPL & non-REPL modes.
I think this works exactly how you want it to already. Here's my REPL session:
scala> case class A(val s: String)
defined class A
scala> object A {
| def apply(s: String) = new A(s.toUpperCase)
| }
defined module A
scala> A("hello")
res0: A = A(HELLO)
This is using Scala 2.8.1.final

Is it possible to inherit auxiliary constructors in Scala?

I wonder if it is possible to inherit auxiliary constructors in Scala?
I tested this code, and it complained
temp.scala:18: error: too many arguments for constructor Child: ()this.Child
val a = new Child(42)
^
abstract class Father {
var value: Int = 0
protected def setValue(v: Int) = {
value = v
}
protected def this(v: Int) = {
this()
setValue(v)
}
}
class Child extends Father {
}
val a = new Child(42)
But if i put
protected def this(v: Int) = {
this()
setValue(v)
}
in the Child class, everything is all right.
Absolutely not, and your example demonstrates why. You've introduced a mutable variable value that may or may not be initialised - depending on the exact constructor used.
This is a potential source for a great many problems, and so Scala made the decision that all object creation should ultimately be directed via the primary constructor, this ensuring consistent initialisation.
If you want value to have a default value, then you can specify it as a default parameter (in 2.8+):
abstract class Father(val value : Int = 0)
or you can use the auxiluary constructor to achieve the same effect in Scala 2.7:
abstract class Father(val value : Int) {
def this() = this(0)
}
With Father defined in either of the above ways, the following definitions of child are both valid:
class Child(v:Int) extends Father(v)
class Child extends Father()
You can also make value a var if you absolutely have to, but I strongly advise against it.
If the semantics of value mean that it's valid to not be initialised, then the correct Scala idiom is to declare it as Option[Int]:
abstract class Father(val value : Option[Int] = Some(0))
Your Child constructor have no parameter and you are trying to instanciate it with one ! You have to declare a parameter in your Child constructor and then pass it to the Father class, for example:
class Child(v:Int) extends Father(v) {
}
val a = new Child(42)