Can you combine named parameter with short-hand constructor parameter? - constructor

In dart:
Named parameters function like so-
String send(msg, {rate: 'First Class'}) {
return '${msg} was sent via ${rate}';
}
// you can use named parameters if the argument is optional
send("I'm poor", rate:'4th class'); // == "I'm poor was sent via 4th class"
Short-hand constructor parameters function like so-
class Person {
String name;
// parameters prefixed by 'this.' will assign to
// instance variables automatically
Person(this.name);
}
Is there any way to do something like the below?-
class Person{
String name;
String age;
Person({this.name = "defaultName", this.age = "defaultAge"});
}
//So that I could do something like:
var personAlpha = new Person(name: "Jordan");
Thanks,
Code samples borrowed from dartlang synonyms

Update
Yes, the = is allowed in Dart 2 and is now preferred over the : to match optional positional parameters.
Person({this.name = "defaultName", this.age = "defaultAge"});
Old Answer
You just have to use a colon instead of equals
class Person {
String name;
String age;
Person({this.name: "defaultName", this.age: "defaultAge"});
}
I find this still confusing that optional parameters use = to assign defaults but named use :.
Should ask myself.

You can use the "this." syntax with all argument types.
As answered above, you need ':' for default values for named parameters.
You can even use "this." for function typed parameters:
class C {
Function bar;
C({int this.bar(int x) : foo});
static foo(int x) => x + 1;
}

You can also add an required field to skip the default initialization, like so:
class ProcessArguments {
final String logoImagePath;
final String textLogoImagePath;
ProcessArguments({required this.logoImagePath, required this.textLogoImagePath});
}

Related

Is it possible to replace {} with a backspace for localizations

We are using flutter easy localizations and we have texts that use arguments. So for example we have a string in our localizations doc like below,
{
"someAppText":"This is {} app text {}."
}
But sometimes the argument will be empty. Which will result in the following text
This is[SPACE][SPACE]app text[SPACE].
Where the spaces are still there. Is it possible to do a backspace whenever we have no arguments?
Firstly, what about using plural? Sounds like you want to have a different text for different kind of data. I do not come up with other examples when an arg will be empty, so if it is not your case could you please give a concrete example?
Secondly, you can do simple string manipulation as follows (pseudocode). The code only demonstrates the simplest case (to make it brief), but it is trivial to extend to the full case.
String myTranslate(String formatString, List<String> args) {
const EMPTY_MARKER = 'EMPTY_MARKER';
final transformedArgs = args.map((arg) => arg.isEmpty ? EMPTY_MARKER : arg).toList();
final rawString = formatString.tr(transformedArgs);
return rawString.replaceAll(' $EMPTY_MARKER', '');
}
Then in your example, it will output: This is[SPACE]app text.
we can not add any methods inside a JSON file, and only have to use it's simple map<String, String> data
so
a work around solution would use special strings inside the JSON to be able to detect and process them in run time
let's say JSON would have this
{
"someAppText": "This is #VAR01 app text #VAR02."
}
then let us create another class that has methods to handle these special words, they should detect them, and replace them with other dynamic inputs
so
class JSONWorkAround {
/// A - need to define the string pattern we are using in the string which I assumed to look like '#VAR00'
/// let's call them jsonVariables
/// NOTE : if you would like to name them #VAR000 ,, then regExp would be r'#VAR...'
static RegExp regExp = RegExp(r'#VAR..');
/// B - let's make a tracker for any word that matches this regExp in any input string
static List<String> _searchJSONVariablesByRegExp({#required String text, #required RegExp regExp}){
List<String> _strings;
/// always check if not null before we do stuff to avoid errors and save performance
if (text != null){
_strings = regExp.allMatches(text).map((m) => m.group(0)).toList();
}
return _strings;
}
/// C - let's make the tracker specifically for those JSONVariables from a string received from the JSON doc "let's call it rawString"
static List<String> _searchJSONVariablesFromRawString({#required String rawString}){
final List<String> _jsonVariables = _searchJSONVariablesByRegExp(text: rawString, regExp: regExp);
return _jsonVariables;
}
/// E - let's see what to do with the search result
static List<SpecialWord> _processJSONVariables(List<String> jsonVariables){
List<SpecialWord> _outputSpecialWords = <SpecialWord>[];
/// so w notice we will need to process each one alone,, so we loop them out
if(jsonVariables != null && jsonVariables.isNotEmpty){
jsonVariables.forEach((jsonVariable) {
/// we should receive a substitute string instead of that #VAR00 special string,, so ..
/// actually we need to receive a string that is accompanied with its cipher special thing to be able to go back to the sentence and change it,,, like using this special #VAR00 thing as ID
/// and I don't like map<String, dynamic> but I would rather create a model class ,, will be written down there at the end of this class
final SpecialWord _substitute = _processSingleJSONVariable(jsonVariable: jsonVariable);
/// then we add them to the output List
if (_substitute != null){
_outputSpecialWords.add(_substitute);
}
});
}
return _outputSpecialWords;
}
/// D - need to receive both the substitute and its (JSONSpecialVariable / ID) to be able to search for it and process it in the original string
static SpecialWord _processSingleJSONVariable({#required String jsonVariable}){
final SpecialWord _substitute = SpecialWord.getSpecialWordFromAllSpecialWordsByID(jsonVariable);
return _substitute;
}
/// F - finally after receiving the substitutes inside a list<SpecialWord>,, we get get back the original String with the substitutes
static String processJSONStringThatContainsThoseSpecialVariables(String rawString){
/// this has to initialize with the initial raw string value to be processed
String _processedString = rawString;
final List<String> _jsonVariables = _searchJSONVariablesFromRawString(rawString: rawString);
if (_jsonVariables != null && _jsonVariables.isNotEmpty){
final List<SpecialWord> _specialWords = _processJSONVariables(_jsonVariables);
/// then we need to change each jsonVariable with its substitute
_specialWords.forEach((specialWord) {
_processedString = _replaceSubStringWith(
subStringToReplace: specialWord.id,
replacement: specialWord.substitute,
input: _processedString,
);
});
}
return _processedString;
}
/// G - a text replacing method to easily replace a given subString from a string with another value
static String _replaceSubStringWith({#required String subStringToReplace, #required String replacement, #required String input}){
final String _output = input.replaceAll(subStringToReplace, replacement);
return _output;
}
}
class SpecialWord{
final String id;
final String substitute; // you can change this to be more complex to adapt to many languages or other things
const SpecialWord({
#required this.id,
#required this.substitute,
});
/// lets create a list of constants that u may change in future and call from db or wherever
static const List<SpecialWord> _allSpecialWords = const <SpecialWord>[
SpecialWord(id: '#VAR01', substitute: 'Baby'),
SpecialWord(id: '#VAR02', substitute: 'Cool'),
SpecialWord(id: '#VAR03', substitute: 'You got the Idea'),
];
/// I like to pamper myself with super quick methods to be clean and organized
static SpecialWord getSpecialWordFromAllSpecialWordsByID(String id){
SpecialWord _foundWord;
if (id != null){
_foundWord = _allSpecialWords.firstWhere((word) => word.id == id, orElse: () => null);
}
return _foundWord;
}
}
then lets make a little method test to assure the safety of this boiler plate over engineered code
test("Testing JSON Variables work around idea", () async {
String _rawString = "This is #VAR01 app text #VAR02.";
String _processedString = JSONWorkAround.processJSONStringThatContainsThoseSpecialVariables(_rawString);
String _expectation = "This is Baby app text Cool.";
expect(_processedString, _expectation);
});
But now you might ask yourself,, is it worth it,, did I over engineer things,, is there a wiser solution ?,, maybe just save each case in json from the start,, I don't know,,
I'm afraid I over complicated the solution,, but it works like a charm
I am not sure i understood your issue. But try the following.
Add two translations one for the empty argument someAppTextEmpty and one for the regular one someAppText
{
"someAppText": "This is {} app text {}.",
"someAppTextEmpty": "This is the alternative app text."
}
Then check if the argument is empty or not to get the right translation key:
final String translationKey = argument.isNotEmpty
? 'someAppText' : 'someAppTextEmpty';
Then pass the variable translationKey to the translation function of easy_localization like this:
final String title = tr(translationKey);
// Or
Text(translationKey).tr();
// Or
translationKey.tr();
No.
With or without easy_localization, the backspace character in Dart takes 1 space in a String instead of deleting 1 space. That is my conclusion through trial and error.
My suggestion:
Create a string called BACKSPACE with a never used value starting by a space eg:
final String BACKSPACE = 'NEVER_USED_VALUE';
When appropriate, assign BACKSPACE to value1 and value2 instead of an empty string.
Then, do this:
'someAppText'.tr(value1, value2).replaceAll(' ' + BACKSPACE, '');

No match found for function signature when NullHandling set to INTERNAL

I'm trying to implement an user defined function for Apache Drill.
The function takes float arguments (decimals do not work) and they have to be nullable in order to return zeroes.
However, when I use NullHandling.Internal and set the parameters as nullable types, the function can be no longer invoked.
SELECT tetsting_udf(1.23,4.56);
VALIDATION ERROR: (...): No match found for function signature TESTING_UDF(<DECIMAL>, <DECIMAL>)
SELECT tetsting_udf(cast(1.23 as float), cast(4.56 as float));
VALIDATION ERROR: (...): No match found for function signature TESTING_UDF(<FLOAT>, <FLOAT>)
When Float8Holders and NullHandling.NULL_IF_NULL is used, both calls above are working.
What I'm doing wrong?
#FunctionTemplate(
name = "testing_udf",
scope = FunctionTemplate.FunctionScope.SIMPLE,
nulls = FunctionTemplate.NullHandling.INTERNAL
)
public class TestingFunction implements DrillSimpleFunc {
#Param
NullableFloat8Holder numberA;
#Param
NullableFloat8Holder numberB;
#Output
Float8Holder out;
public void setup() {
}
public void eval() {
// Whatever
}
}
For the case when FunctionTemplate.NullHandling.INTERNAL is specified, UDFs implementations with all combinations of nullability should be specified. For your case, you should specify UDFs which accepts (Float8Holder and Float8Holder), (NullableFloat8Holder and NullableFloat8Holder), (Float8Holder and NullableFloat8Holder), (NullableFloat8Holder and Float8Holder).

Lower casing column values dynamically

I have a mysql script and I want to convert a column value to be always in lower case. I don't want to use trigger. When I run my hibernate code and fill data in DB I want a column value to be always in lowercase.
Is there is any way I can use Lower() function of mysql during table creation so that every time data is inserted it is lower Case?
I saw many examples of lowercase but all are update operation.
You can use Hibernate interceptor (see an example here)
In the method
public boolean onSave(Object entity,Serializable id,
Object[] state,String[] propertyNames,Type[] types)
You can check whether the entity is instance of your class to be lowercased and update necessary fields with lower cased values.
Or just in the entity extend setters to convert to the lowercase on call.
Assume you have an entity like:
#Entity
#EntityListeners(MyEntityListener.class)
public class MyEntity {
private String name;
...
}
and EntityListener like:
import javax.persistence.PrePersist;
public class MyEntityListener {
#PrePersist
public void entityPrePersist(MyEntity obj) {
if (obj != null && obj.getName() != null) {
obj.setName(obj.getName().toLowerCase());
}
// ... same to other properties
}
}

How can I modify val members during construction in Kotlin

In Java I'm able to modify final members in the constructor. Please see the following example
class Scratch {
private final String strMember;
public Scratch(String strParam) {
this.strMember = strParam.trim();
}
}
Is there a way in Kotlin to modify val members during construction, in this case to trim() them before the parameter value are assigned to the field.
If not, what is the recommended workaround to do so without generating too much overhead?
You can declare an argument to the constructor that isn't marked with val or var. This has the effect of being local to the constructor and lost once class construction is complete. Take that argument and set it to whatever you want.
class Scratch(str: String) {
private val strMember = str.trim()
}
Like this: constructor parameters are available during initialization of properties.
class Scratch(strParam:String) {
private val strMember = strParam.trim()
}
Try your strParam final property as follow
class Scratch(strParam : String) {
val strParam : String = strParam
get() = field.trim()
}
So, you can use them inside and outside your Scratch class

Proper usage of "this." keyword in C#?

I'm working through the book Head First C# (and it's going well so far), but I'm having a lot of trouble wrapping my head around the syntax involved with using the "this." keyword.
Conceptually, I get that I'm supposed to use it to avoid having a parameter mask a field of the same name, but I'm having trouble actually tracking it through their examples (also, they don't seem to have a section dedicated to that particular keyword, they just explain it and start using it in their examples).
Does anyone have any good rules of thumb they follow when applying "this."? Or any tutorials online that explain it in a different way that Head First C#?
Thanks!
Personally I only use it when I have to which is:
Constructor chaining:
public Foo(int x) : this(x, null)
{
}
public Foo(int x, string name)
{
...
}
Copying from a parameter name into a field (not as common in C# as in Java, as you'd usually use a property - but common in constructors)
public void SetName(string name)
{
// Just "name = name" would be no-op; within this method,
// "name" refers to the parameter, not the field
this.name = name;
}
Referring to this object without any members involved:
Console.WriteLine(this);
Declaring an extension method:
public static TimeSpan Days(this int days)
{
return TimeSpan.FromDays(days);
}
Some other people always use it (e.g. for other method calls) - personally I find that clutters things up a bit.
StyleCop's default coding style enforces the following rule:
A1101: The call to {method or property
name} must begin with the 'this.'
prefix to indicate that the item is a
member of the class.
Which means that every method, field, property that belongs to the current class will be prefixed by this. I was initially resistant to this rule, which makes your code more verbose, but it has grown on me since, as it makes the code pretty clear. This thread discusses the question.
I write this. if and only if it enhances readability, for example, when implementing a Comparable interface (Java, but the idea is the same):
public void compareTo(MyClass other) {
if (this.someField > other.someField) return 1;
if (this.someField < other.someField) return -1;
return 0;
}
As to parameter shadowing (e.g. in constructors): I usually give those a shorter name of the corresponding field, such as:
class Rect {
private int width, height;
public Rect(int w, int h) {
width = w;
height = h;
}
}
Basically, this gives you a reference to the current object. You can use it to access members on the object, or to pass the current object as parameters into other methods.
It is entirely unnecessary in almost all cases to place it before accessing member variables or method calls, although some style guidelines recommend it for various reasons.
Personally, I make sure I name my member variables to be clearly different from my parameters to avoid ever having to use 'this.'. For example:
private String _someData;
public String SomeData
{
get{return _someData;}
set{_someData = value;}
}
It's very much an individual preference though, and some people will recommend that you name the property and member variable the same (just case difference - 'someData' and 'SomeData') and use the this keyword when accessing the private member to indicate the difference.
So as for a rule of thumb - Avoid using it. If you find yourself using it to distinguish between local/parameters variables and member variables then rename one of them so you don't have to use 'this'.
The cases where I would use it are multiple constructors, passing a reference to other methods and in extension methods. (See Jon's answer for examples)
If you have a method inside a class which uses same class's fields, you can use this.
public class FullName
{
public string fn { set; get; }
public string sn { set; get; }
//overriding Equals method
public override bool Equals(object obj)
{
if (!(obj is FullName))
return false;
if (obj == null)
return false;
return this.fn == ((FullName)obj).fn &&
this.sn == ((FullName)obj).sn;
}
//overriding GetHashCode
public override int GetHashCode()
{
return this.fn.GetHashCode() ^ this.sn.GetHashCode();
}
}