Auto Class Completion of all the classes of a unit - class

I've created a function to extract Objects from a special JSON file extracted from SwaggerHub and create a unit for them. My functions is like this:
CreateUnit('d:\a.json', 'd:\MyAPI.pas');
And creates a unit like this:
unit MyAPI;
interface
type
TType1 = class;
TType2 = class;
TType3 = class;
...
TType1 = class
property p1: TType1;
property p2: TType2;
property p3: String;
property p4: Integer;
end;
TType2 = class
property p1: TType1;
property p2: TType3;
property p3: String;
property p4: Integer;
property p5: Integer;
property p6: string;
end;
...
implementation
end.
This unit contains 133 classes and I want to apply the "Complete Class at Cursor" (Shift+Ctrl+C) on all classes. If I do it one by one, it takes a lot of time because every time I press Shift+Ctrl+C the cursor jumps to the bottom of the unit and I must go up and find the next uncompleted class.
Is there any Idea?

Related

Trying to implement a UUID(random unique identifier) generated from a method

New to scala, what is the best way to implement this method. I am trying to get this value output from the method below and assign it to a case class. Bit rusty on the OOP practices.
/** A container for storing car table fields */
case class car(
UUID??
color:String,
model:String,
type:String,
)
Basicaly my question what is the best way to create an instance of the below rand value to the case class car above. Create another class and call it or implement with in the same scala class?
def rand = new Random()
def randomClockSeqAndNodeFields = {
var lsb: Long = 0
lsb |= 0x8000000000000000L // variant (2 bits)
lsb |= ( rand.synchronized { rand.nextLong } & 0x3FFFFFFFFFFFFFFFL)
lsb
}
I suggest, since UUID is a java supported type :
/** A container for storing car table fields */
case class car(
uuid: UUID = UUID.randomUUID(),
color:String,
model:String,
type:String,
)
One way to organize this code is to define a companion object:
object Car {
def rand = new Random()
def randomClockSeqAndNodeFields = { ... }
}
case class Car(
UUID: Long = Car.randomClockSeqAndNodeFields,
color: String,
model: String,
make: String
)
You can call your method inside the declaration of your case class, and that method will, by default, be called for every instance of the class. Note that I capitalized the class name to follow standard naming conventions, and I renamed type to make because type is a keyword.
To create a Car instance:
val myCar = Car(color="black", model="wrangler", make="jeep")
The creation of every Car instance, if you don't explicitly pass in a value for the UUID parameter, will call randomClockSeqAndNodeFields, generating a new UUID for that car. Alternatively, you could define Car as...
case class Car(
UUID: Long,
color: String,
model: String,
make: String
)
...in which case you'd have to explicitly call randomClockSeqAndNodeFields every time you create an instance:
val myCar = Car(Car.randomClockSeqAndNodeFields, "black", "wrangler", "jeep")

Scala adding an extra function to a Class

I encountered the following code while checking through a Scala code. I'm finding it difficult to understand what it does.
class Foo(val name: String, val age: Int, val sex: Symbol)
object Foo {
def apply(name: String, age: Int, sex: Symbol) = new Foo(name, age, sex)
}
Does it add a constructor method to the Class Foo which was already defined?
Is it possible to add extra methods to classes which are already defined using this syntax?
Does it add a constructor method to the Class Foo which was already
defined?
It adds syntax sugar to the class. Meaning, you can create an instance of Foo like this:
val foo = Foo()
Instead of
val foo = new Foo()
Is it possible to add extra methods to classes which are already
defined using this syntax?
In that regards, apply is special as the compiler knows it and expands Foo() to Foo.apply. This means that any other method you want to invoke, you'll have to call the Foo static object, but they will not apply to the Foo instance.
If you want to externally add methods to Foo, you can do so via an implicit class:
implicit class RichFoo(foo: Foo) extends AnyVal {
def fooDetails(): String = s"{Name: ${foo.name}, Age: ${foo.Age}"
}
Now you can call it on an instance of Foo:
val f = Foo()
println(f.fooDetails())
In the case, you can think of Foo.apply() as a static method.
Realistically, objects in Scala are implemented as Singleton instances.
Here's the documentation on that.
You can invoke any class or object instance in Scala if it has an apply method. What you're doing here is adding a constructor method to Foo's companion object so that when you call it, it will instantiate an instance of Foo.
It is not possible to add methods to an instance with this method. For that, you might be interested in the Scala Pimp My Library pattern which is implemented using implicits.
// the following are equivalent, given your code above
val x = new Foo("Jason", 29, 'Male)
val y = Foo.apply("Jason", 29, 'Male)
val z = Foo("Jason", 29, 'Male)
Please read about companion object: http://docs.scala-lang.org/tutorials/tour/singleton-objects.html hope this helps
It simplifies object creation for this type. Other way will be to create case class.
Looks like as duplicate to me:
Scala: companion object purpose
This pattern is commonly know as static factory methods. The code you provided is not very useful, but consider these additional factory methods (think of them as "named constructors"):
class Foo(val name: String, val age: Int, val sex: Symbol)
object Foo {
def apply(name: String, age: Int, sex: Symbol) = new Foo(name, age, sex)
def newMaleFoo(name:String,age:int) = new Foo(name,age,'male)
def newPeterFoo(age:int) = new Foo("Peter",age,'male)
}

calling a function inside of a constructor in scala

I am calling a function inside of class constructor but while compiling the code I keep getting an error : not found value : churnPeriodfnc
here is the code that I am running
class CustStoryN (var custId:String,
var rootEventType:String,
var rootEventTime:Long,
var eventStory:mutable.MutableList[StoryEventN]) extends Serializable {
def this(custID: String,rootEventType: String, rootEventTim: Long, eventStory: mutable.MutableList[StoryEventN], churnPeriod: Boolean, churnMode: Boolean)
{
this(custID,rootEventType,rootEventTim,
churnPeriodfnc(churnPeriod, churnMode,eventStory))
}
and here is ChurnPeriodFnc function that the compiler can not recognize, I didnt copy the churn periodfunc , for now just assume that I make some changes to eventstory and out put a new eventstory:
def churnPeriodfnc(churnPeriod: Boolean, churnMode: Boolean, eventStory: mutable.MutableList[StoryEventN]): mutable.MutableList[StoryEventN] = {
eventStory }
If churnPeriodfnc is defined within class body (instance method) or it is inherited; you can't call it inside a constructor.
If churnPeriodfnc is defined inside CustStoryN's companion object (like a static method); you must either import it or refer to it as CustStoryN.churnPeriodfnc()
If it's defined in another object, above rule still applies.
I have encountered a similar problem and I don't find this behavior logic (I understand that there is no instance of the class and the function does not exist yet but hey, the function is there inside the class I'm trying to instantiate.)
To fix the problem I suggest you using an apply function in the companion object like this:
case class Human(id: Int, name: String)
object Human {
def apply(id: Int): Human = new Human(id, withName(id))
def withName(id: Int): String = "Goku" /* Some behavior to get the name */
}
If you try this in your REPL you should have a behavior like this:
scala> Human(3)
res0: Human = Human(3,Goku)

Can I in Scala declare the class inside its companion object?

While fighting with my private immutable class constructor, and the constraint that auxiliary constructors have to call each other as first statement, without anything else from the class in scope, I seem to be constrained to use a companion object for my instantiations, and since my companion object would have to access the main constructor, I need the private keyword to target a scope including that object.
Now, my brain is weak in name generation, and I am trying to save the need of an enclosing namespace for both that companion object and the class by placing my class within the companion object itself, this way:
object Group {
private def complexComputeX(z: Int) = z
private def complexComputeY(x: Int, z: Int) = x + z
def apply(z: Int) = {
val x = complexComputeX(z)
val y = complexComputeY(x, z)
new Group(x, y)
}
class Group private[Group](x: Int, y: Int) {
//...
}
}
val x = Group(5)
//...
The problem is that the Group of private[Group] does not reference the object, but still the class (making it superfluous).
How can I tag that constructor to be available at the companion object level, but not outside it?
PS: that companion object is already giving me headache, and I would even have preferred to have just the class, en-scoping there the complexCompute, which several constructors implementations could need...
EDIT: Okay. Just while adding the tags I hit a neuron ringing me that a companion object might have some privilege over the class' scope. It can access its private parts, and so I can simply have object and class side to side without dedicated enclosing scope. However, I maintain the question, for both a response on possibility way to handle scoping for such boxing cases object Main {object Main {object Main... and for chances of remarks about techniques for having only constructors in the class without any companion object.
Your Group object is not the companion object of your Group class as they are not in the same namespace.
You don't have to provide a scope to the private modifier. If you leave it empty, it's only accessible by this class and its companion object.
object Something {
class Group private(x: Int, y: Int)
object Group {
private def complexComputeX(z: Int) = z
private def complexComputeY(x: Int, z: Int) = x + z
def apply(z: Int) = {
val x = complexComputeX(z)
val y = complexComputeY(x, z)
new Group(x, y)
}
}
val x = Group(5)
// This line doesn't compile
new Group(42, 45)
}
The companion object's private are also accessible from the class, so I have this other option, concerning my root problem:
object Group {
private def computeX(z: Int) = z
private def computeY(x: Int, z: Int) = x + z
private def computeXY(z: Int) = {
val x = computeX(z)
(x, computeY(x, z))
}
}
class Group private (x: Int, y: Int) {
private def this(xy: (Int, Int)) = this(xy._1, xy._2)
def this(z: Int) = this(Group.computeXY(z))
}
val group = new Group(5)
That the companion object makes a full privatable scope available from my constructors makes me breath better. In my full case I was indeed also going to need types I wanted private too. The fact that I am forced to create a companion to contain this locally useful scope might not be so important now, I guess.
However, the use of the tuple makes it more cumbersome than Dimitri's option.

How to define accessor method for default constructor parameter?

Trying to define an accessor method for default constructor parameter, i.e.:
class Person (age: Int) {
def age: Int = this.age
}
Which obviously results in a compiler error: ambiguous reference to overloaded definition, both method age in class Person of type => Int and value age in class Person of type Int match expected type Int
Is there a way in this context to distinguish between the member method name and auto-generated member value name?
Of course it's possible to change the name of either identifier, but is there a way in this scenario of actually specifying which identifier is referred to?
Just put "val" in front of constructor parameters that you want to expose as instance properties.
Use
class Person (val age: Int)
if you just want a getter or
class Person (var age: Int)
if you also want a setter.
The answers above are great wrt the uniform access principle. If you have or need Java style getters and setters you can also use the BeanProperty annotation.
class Person(#scala.reflect.BeanProperty var age: Int)
This will result in the following methods being created:
def getAge: Int = age
def setAge(age: Int) = this.age = age
If you instead use the BeanProperty for a val instead of a var, the setter won't be created, only the getter.
One other caveat, the setter method cannot be called from inside Scala. Instead, you should use the standard Scala convention of uniform access to set the value.
Just for completeness and to expand on the previous answers, there is also the technique covered here.
To summarize, I would always begin with an immutable value:
class Person (val age: Int)
Then, if you figure out you need to mutate the value (or you know it in advance), switch to:
class Person (var age: Int)
Then, if you need to validate or do some other computation on get or set, rename your variable and build accessors that mimic your original naming, no need to refactor the rest of the code:
class Person(var _age: Int)
{
def age =
{
println("age requested")
_age
}
def age_=(newAge: Int) =
{
assert(newAge > 0)
println(s"age changed from ${_age} to $newAge")
_age = newAge
}
}
Of course, you can simplify either setter or getter if you don't need operations there.
Kudos to all other answers, which are indeed correct and came much sooner.