Groovydoc: Documenting named parameters - groovy

I've created a method like so:
void myMethod(Map kwArgs, def myParam)
{
println kwArgs.firstName
println [kwArgs.lastName, "Wilcox"].find()
// ^^^ if lastName named parameter not specified, "Wilcox"
....
}
Now comes the time to document this method with GroovyDoc. Part of it is easy
/**
myMethod rules the world
#param myParam something something
But how do I document the named parameters? (Likewise, how can I specify that the lastName parameter has a default? (ie is there some metadata I can set or just make that explicit to the reader in the English description?)

But how do I document the named parameters?
Unless you are considering writing a customer doclet or similar, I think you will just document them as text in the comment.

Related

Unable to display the age of an object that was passed to a kotlin function

I'm just starting to learn kotlin and ran into a problem:
I have a Person class that has two fields
-age (Int data type)
-name (data type String)
there is also a oldUp function where I pass a Person object and increment the object's age field by 10.
Before the end of the program ** I want to display the age of the object that was passed to oldUp **
However, age is not shown.
my code:
class Person(var name: String, var age: Int){
}
fun growOld(human: Person){
human.age+=10
}
fun main(args: Array<String>) {
var human = Person("Kitty",6)
growOld(human)
println(human)
}
If you want to print the age, you can just write: println(human.age).
In your example it might be cleaner to add the growOld method to your class so you can call it on the object. For example:
class Person(var name: String, var age: Int){
fun growOld() {
this.age += 10
}
}
fun main() {
var human = Person("Kitty", 6)
println(human.age) // prints 6
human.growOld()
println(human.age) // prints 16
println(human.name) // prints Kitty
}
The problem is you're trying to print the human object itself. Under the hood, this calls its toString() method - every class has one of these, because it's defined on the type all classes derive from. If you don't override it and provide a nice way to "pretty print" your object, it'll use the default implementation, which is basically a reference to the object in memory.
A lot of classes you use have a nice toString() implementation, e.g. if you print a List you get ["something", "that", "looks", "like", "this"]. But that behaviour needed to be coded in - and you need to do that for your Person class too!
So you can override the default implementation like this:
override fun toString(): String {
// return a String here
}
override means you're taking an existing function and writing your own version of it to use instead - if this doesn't match an existing function you can override, you'll get an error. You'll also get an error if you don't use the override keyword for a function that looks exactly like an existing one in a supertype - it's just to make sure you don't accidentally do the wrong thing. In IntelliJ you can do Ctrl+O to override existing functions if you like.
So you could do something like this:
// inside your Person class
override fun toString(): String {
return "Name: $name, age: $age"
}
and then when you use it in a print statement, or in a string (like "Details: $person" or val details = "Details: " + person) it will call that toString() method and get the string you produced.
Another way to approach this is to use a data class:
data class Person(var name: String, var age: Int)
A data class is a special kind of class where all your "data" goes in the constructor (as properties, either val or var), and then you get some boilerplate stuff for free which uses those properties (and only those properties). Things like an equals() and hashCode() implementation that uses that data - and the relevant thing here, it gives you a toString() implementation that pretty prints name and age. Try it out!
Data classes can be really handy for simple data objects like you have here - but in normal classes, overriding toString() yourself is the general way of doing things. And you can still override a data class's toString if you want - sometimes you might want a more complex representation, or nice formatting, or you might want to only include some properties and ignore others. You're in control of how it prints itself!
And if you just want to print the age property, or print anything at all using the data in your object, then you just need to do what Robin's answer says. You don't need a toString() implementation at all for that (and since this is how you usually use objects, often you won't need to write a toString for your own classes at all)

IntelliJ Live Template for dart named constructor: lists class' fields

I want to generate a custom named constructor in Dart.
I have many dto class to implement and each should provide a named constructor like: ClassName.fromMap().
For example for this class:
class Student {
final String name;
final int age;
}
The generated constructor should be:
Student.fromMap(Map<String, dynamic> map) :
name = map['name'],
age = map['age'];
How can I retrieve the list of the field of my current class as strings? Is that even possibile?
Of course I can have a variable number of fields.
My template looks like:
$CLASS$.fromMap(Map<String, dynamic> map) :
$INITIALIZATION_LIST$
binding $CLASS$ to dartClassName().
Now I'd like to bind $INITIALIZATION_LIST$ to something like:
getClassFieldList().forEach((fieldName) => "$fieldName = map['$fieldName']")
Can I achieve something like that?
There is no way to retrieve a list of Dart class fields using predefined live template functions. You can try developing your own template macro for this. See https://intellij-support.jetbrains.com/hc/en-us/community/posts/206201699-create-a-new-expression-for-a-live-template-for-actionscript for some hints.
Existing live template functions implementations can be found at https://github.com/JetBrains/intellij-community/tree/master/platform/lang-impl/src/com/intellij/codeInsight/template/macro.
You can also try using Structural Search and Replace instead of live template

Is it possible to get the name of variable in Groovy?

I would like to know if it is possible to retrieve the name of a variable.
For example if I have a method:
def printSomething(def something){
//instead of having the literal String something, I want to be able to use the name of the variable that was passed
println('something is: ' + something)
}
If I call this method as follows:
def ordinary = 58
printSomething(ordinary)
I want to get:
ordinary is 58
On the other hand if I call this method like this:
def extraOrdinary = 67
printSomething(extraOrdinary)
I want to get:
extraOrdinary is 67
Edit
I need the variable name because I have this snippet of code which runs before each TestSuite in Katalon Studio, basically it gives you the flexibility of passing GlobalVariables using a katalon.features file. The idea is from: kazurayam/KatalonPropertiesDemo
#BeforeTestSuite
def sampleBeforeTestSuite(TestSuiteContext testSuiteContext) {
KatalonProperties props = new KatalonProperties()
// get appropriate value for GlobalVariable.hostname loaded from katalon.properties files
WebUI.comment(">>> GlobalVariable.G_Url default value: \'${GlobalVariable.G_Url}\'");
//gets the internal value of GlobalVariable.G_Url, if it's empty then use the one from katalon.features file
String preferedHostname = props.getProperty('GlobalVariable.G_Url')
if (preferedHostname != null) {
GlobalVariable.G_Url = preferedHostname;
WebUI.comment(">>> GlobalVariable.G_Url new value: \'${preferedHostname}\'");
} else {
WebUI.comment(">>> GlobalVariable.G_Url stays unchanged");
}
//doing the same for other variables is a lot of duplicate code
}
Now this only handles 1 variable value, if I do this for say 20 variables, that is a lot of duplicate code, so I wanted to create a helper function:
def setProperty(KatalonProperties props, GlobalVariable var){
WebUI.comment(">>> " + var.getName()" + default value: \'${var}\'");
//gets the internal value of var, if it's null then use the one from katalon.features file
GlobalVariable preferedVar = props.getProperty(var.getName())
if (preferedVar != null) {
var = preferedVar;
WebUI.comment(">>> " + var.getName() + " new value: \'${preferedVar}\'");
} else {
WebUI.comment(">>> " + var.getName() + " stays unchanged");
}
}
Here I just put var.getName() to explain what I am looking for, that is just a method I assume.
Yes, this is possible with ASTTransformations or with Macros (Groovy 2.5+).
I currently don't have a proper dev environment, but here are some pointers:
Not that both options are not trivial, are not what I would recommend a Groovy novice and you'll have to do some research. If I remember correctly either option requires a separate build/project from your calling code to work reliable. Also either of them might give you obscure and hard to debug compile time errors, for example when your code expects a variable as parameter but a literal or a method call is passed. So: there be dragons. That being said: I have worked a lot with these things and they can be really fun ;)
Groovy Documentation for Macros
If you are on Groovy 2.5+ you can use Macros. For your use-case take a look at the #Macro methods section. Your Method will have two parameters: MacroContext macroContext, MethodCallExpression callExpression the latter being the interesting one. The MethodCallExpression has the getArguments()-Methods, which allows you to access the Abstract Syntax Tree Nodes that where passed to the method as parameter. In your case that should be a VariableExpression which has the getName() method to give you the name that you're looking for.
Developing AST transformations
This is the more complicated version. You'll still get to the same VariableExpression as with the Macro-Method, but it'll be tedious to get there as you'll have to identify the correct MethodCallExpression yourself. You start from a ClassNode and work your way to the VariableExpression yourself. I would recommend to use a local transformation and create an Annotation. But identifying the correct MethodCallExpression is not trivial.
no. it's not possible.
however think about using map as a parameter and passing name and value of the property:
def printSomething(Map m){
println m
}
printSomething(ordinary:58)
printSomething(extraOrdinary:67)
printSomething(ordinary:11,extraOrdinary:22)
this will output
[ordinary:58]
[extraOrdinary:67]
[ordinary:11, extraOrdinary:22]

Impex Export: Colon in multivalue attribute is escaped by double backslash - How to remove this behavior?

Hybris: 6.3.0.0-SNAPSHOT (the behavior is the same with 6.3.0.21)
When exporting impex, we noticed a difference when exporting a non-multivalue Type attribute versus exporting a multivalue Type attribute.
When exporting String attribute data without colon, a non-multivalue attribute can be exported as Experts, while a multivalue attribute can be exported as Experts|Hybris.
When exporting Type with String attribute data with colons (e.g. URL), the colon is escaped with a double backslash (for multivalue only). A non-multivalue attribute can be exported as https://experts.hybris.com, while a multivale attribute can be exported as https\://experts.hybris.com if there is only 1 value or as https\://experts.hybris.com|https\://help.hybris.com if there are 2 values.
How can I stop the export from escaping the colon? Is there a method I can override to change this behavior? I would like to change the result to https://experts.hybris.com|https://help.hybris.com or to "https://experts.hybris.com"|"https://help.hybris.com".
Business Case: We want to copy the URL from the exported impex, but the URL contains double backslashes. The exported impex is not meant to be reimported.
Notes #`: The URLs are stored in a collection (e.g. Product.newAttribute, where newAttribute is a collection of custom types which has a String). So, the Impex header looks something like "INSERT_UPDATE Product;newAttribute(data)"
Notes #2: (UPDATE: Didn't work) Currently, I'm checking if it's possible with a CSVCellDecorator; this is for import only.
Notes #3: Currently, I'm checking if it's possible with AbstractSpecialValueTranslator.
For this specific case, I created a new translator, extending AbstractValueTranslator. Then, I implemented the exportValue method, joining the string data (which are URLs), without escaping them.
public String exportValue(final Object value) throws JaloInvalidParameterException
{
String joinedString = "";
if (value instanceof Collection)
{
final Collection valueCollection = (Collection) value;
if (!valueCollection.isEmpty())
{
final ArrayList<CustomType> list = (ArrayList<CustomType>) valueCollection;
final StringJoiner joiner = new StringJoiner("|");
for (final CustomType customType : list)
{
// data is a URL
joiner.add(customType.getData());
}
// value would be something like "https://experts.hybris.com|https://help.hybris.com"
joinedString = joiner.toString();
}
}
return joinedString;
}
Reference:
Customization: https://help.hybris.com/1808/hcd/ef51040168d743879c015b7de232ce40.html
I think that might not be possible, since the colon is used to separate keys for referenced types. As in
...;catalogVersion(catalog(id),version);...
...;myCatalog:Staged;...
Why not run search/replace on the result?

Alternatives to boxing string field or extending ALL strings in Kotlin?

Given that one can't subclass builtin types in Kotlin, I'm looking for a way to add special method functionality to specific types of string fields in a record, without applying those extension functions to all strings (even within that record type). Say, for example, I have some mutable string fields inside a record, for which I want to define special purpose behaviors.
class Customer {
// ...
var zipcode: String
var email: String
// ...
}
For zipcode, assume I'd like to be able to call
thisCustomer.zipcode.plusFour to get the +4 of the zip code (99999-9999) via regex.
For email, assume I'd like to be able to call
thisCustomer.email.domain to have a regex go get the ...#company.com
portion of the specified email.
My objectives are to:
Avoid the runtime overhead of boxing zipcode into a class Zipcode with just a
single var inside, given that the size of the Customer recordset could potentailly be millions.
Avoid the syntax of having to assign
thisCustomer.zipcode.value = "99999-9999" or thisCustomer.zipcode = Zipcode("99999-9999"), if I did end up having to box the string.
Avoid adding general String.plusFour and
String.domain extension properties, even just within the Customer
class... because zipcodes and emails could technically call each others'
extensions
I've been thinking this over and considered the following options, but struck out with each:
subclassing String: Not possible since strings (and all built-ins)
are closed
applying an interface Zip to the var declaration (var zipcode:
String, Zip): No such syntax I could find
adding inner functions within the getter itself: Syntax doesn't seem to exist for this
using objects or functions-within-functions: Couldn't think of a way
for this to work, although I might not be imaginative enough
Am I missing an obvious solution here? Even if not obvious, with all the syntactic magic of Kotlin, is there a way to make it happen? Maybe there's a way to accomplish some/all of the objectives above without using any of these approaches?
You can use type aliases to make the intention clear:
typealias ZipCode = String
val ZipCode.plusFour get() = ...
typealias Email = String
val Email.domain get() = ...
class Customer {
// ...
var zipcode: ZipCode
var email: Email
// ...
}
Unfortunately, this only clarifies intentions and doesn't stop the compiler from allowing zipcode.domain. But for now I don't think there is any way which satisfies both objectives 1 and 3.
Kotlin developers have decided not to support assignment-incompatible type aliases, which would have fit all your requirements, in favor of waiting for value classes to be available on JVM, as discussed in https://github.com/Kotlin/KEEP/issues/4.
You may create a decorator class using delegate:
class YourString(val value: String) : Comparable<String> by value, CharSequence by value {
val plusFour: String
get() = "" //your logic here
val domain: String
get() = "" //your logic here
override fun toString() = value
}
Usage:
fun String.toYourString() = YourString(this)
class Customer(var zipCode: YourString, var email: YourString)
val customer = Customer("+4 99999-9999".toYourString(), "xxx#company.com".toYourString())
println(customer.zipCode.plusFour)
println(customer.email.domain)

Resources