Kotlin: correct way for read-only getters - kotlin

I have a Java class (simplified) like that
public class Input {
private boolean leftPressed;
private boolean rightPressed;
public void handleValue(Event event) {
if (event.button == 1) {
leftPressed = event.pressed;
}
else if (event.button == 3) {
rightPressed = event.pressed;
}
}
public boolean isLeftPressed() {
return leftPressed;
}
public boolean isRightPressed() {
return rightPressed;
}
}
Note, that the fields only can be changed by code inside handleValue. Would this Kotlin code
class Input {
var leftPressed = false
private set
var rightPressed = false
private set
handleValue(event: Event) {
if (event.button == 1) {
leftPressed = event.pressed;
}
else if (event.button == 3) {
rightPressed = event.pressed;
}
}
}
be the proper way of creating the read-only properties? You really have to add the private set to make it safe/read-only? Are there other/better ways to prevent writing to the field from outside this class?

Related

Why wrap GenericRowWithSchema using InternalRow in Dataset.collectFromPlan

Look at Dataset.collectFromPlan
private def collectFromPlan(plan: SparkPlan): Array[T] = {
val objProj = GenerateSafeProjection.generate(deserializer :: Nil)
plan.executeCollect().map { row =>
objProj(row).get(0, null).asInstanceOf[T]
}
}
the generated code for objProj is:
class SpecificSafeProjection extends org.apache.spark.sql.catalyst.expressions.codegen.BaseProjection {
private Object[] references;
private InternalRow mutableRow;
private Object[] values;
private org.apache.spark.sql.types.StructType schema;
public SpecificSafeProjection(Object[] references) {
this.references = references;
mutableRow = (InternalRow) references[references.length - 1];
schema = (org.apache.spark.sql.types.StructType) references[0];
}
public void initialize(int partitionIndex) {
}
public java.lang.Object apply(java.lang.Object _i) {
........
final org.apache.spark.sql.Row value = new org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema(values, schema);
if (false) {
mutableRow.setNullAt(0);
} else {
mutableRow.update(0, value);
}
return mutableRow;
}
}
And my question is:
The generated method SpecificSafeProjection.apply returns mutableRow: InternalRow who wraps value:GenericRowWithSchema, why not return value:GenericRowWithSchema directly??

Using complex types in RedisTypedClient (ServiceStack Redis)

I have an example where I want to store an object into Redis.
class CyPoint
{
// Fields...
private bool _Done;
private string _Color;
private string _Position;
private long _Id;
public long Id
{
get { return _Id; }
set
{
_Id = value;
}
}
public string Position
{
get { return _Position; }
set
{
_Position = value;
}
}
public string Color
{
get { return _Color; }
set
{
_Color = value;
}
}
public bool Done
{
get { return _Done; }
set
{
_Done = value;
}
}
}
I am using this code to store the data
var redisCyPoint = redis.As<CyPoint>();
var cpt = new CyPoint
{
Id = redisCyPoint.GetNextSequence(),
Position = "new Vector3(200, 300, 0)",
Color = "new Vector3(.5f, .7f, .3f)",
};
redisCyPoint.Store(cpt);
This works as I am storing strings. But when I change position and color to Vector3 (which is: float, float, float) it only saves 0's. It seems that the Store will not work with complex types. Is this a limitation or is there a way to do this?
Struct's are serialized as a single scalar string value as returned by ToString(). You can implement custom support for Structs by implementing a constructor Vector3(string) that can populate itself from its ToString() value, or implement a static ParseJson(string) method.
Otherwise you can specify custom serializer to handle the serialization, e.g:
JsConfig<Vector3>.SerializeFn = v => "{0},{1},{2}".Fmt(v.X,v.Y,v.Z);
JsConfig<Vector3>.DeSerializeFn = s => {
var parts = s.Split(',');
return new Vector3(parts[0],parts[1],parts[2]);
};

Oracle Coherence index not working with ContainsFilter query

I've added an index to a cache. The index uses a custom extractor that extends AbstractExtractor and overrides only the extract method to return a List of Strings. Then I have a ContainsFilter which uses the same custom extractor that looks for the occurence of a single String in the List of Strings. It does not look like my index is being used based on the time it takes to execute my test. What am I doing wrong? Also, is there some debugging I can switch on to see which indices are used?
public class DependencyIdExtractor extends AbstractExtractor {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public Object extract(Object oTarget) {
if (oTarget == null) {
return null;
}
if (oTarget instanceof CacheValue) {
CacheValue cacheValue = (CacheValue)oTarget;
// returns a List of String objects
return cacheValue.getDependencyIds();
}
throw new UnsupportedOperationException();
}
}
Adding the index:
mCache = CacheFactory.getCache(pCacheName);
mCache.addIndex(new DependencyIdExtractor(), false, null);
Performing the ContainsFilter query:
public void invalidateByDependencyId(String pDependencyId) {
ContainsFilter vContainsFilter = new ContainsFilter(new DependencyIdExtractor(), pDependencyId);
#SuppressWarnings("rawtypes")
Set setKeys = mCache.keySet(vContainsFilter);
mCache.keySet().removeAll(setKeys);
}
I solved this by adding a hashCode and equals method implementation to the DependencyIdExtractor class. It is important that you use exactly the same value extractor when adding an index and creating your filter.
public class DependencyIdExtractor extends AbstractExtractor {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public Object extract(Object oTarget) {
if (oTarget == null) {
return null;
}
if (oTarget instanceof CacheValue) {
CacheValue cacheValue = (CacheValue)oTarget;
return cacheValue.getDependencyIds();
}
throw new UnsupportedOperationException();
}
#Override
public int hashCode() {
return 1;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj instanceof DependencyIdExtractor) {
return true;
}
return false;
}
}
To debug Coherence indices/queries, you can generate an explain plan similar to database query explain plans.
http://www.oracle.com/technetwork/tutorials/tutorial-1841899.html
#SuppressWarnings("unchecked")
public void invalidateByDependencyId(String pDependencyId) {
ContainsFilter vContainsFilter = new ContainsFilter(new DependencyIdExtractor(), pDependencyId);
if (mLog.isTraceEnabled()) {
QueryRecorder agent = new QueryRecorder(RecordType.EXPLAIN);
Object resultsExplain = mCache.aggregate(vContainsFilter, agent);
mLog.trace("resultsExplain = \n" + resultsExplain + "\n");
}
#SuppressWarnings("rawtypes")
Set setKeys = mCache.keySet(vContainsFilter);
mCache.keySet().removeAll(setKeys);
}

ArrayList partial integrating one List in another

I have a function that creates regular Objects of a same type and I cannot avoid that step.
When I use List.addAll(*) I will get many "Duplications" that are not equal in sense of Objectivity.
I have a very bad coded solution and want to ask if there could be a better or more effective one maybe with Java-Util-functions and defining a Comparator for that single intermezzo?
Here is my bad smell:
private void addPartial(List<SeMo_WikiArticle> allnewWiki, List<SeMo_WikiArticle> newWiki) {
if(allnewWiki.isEmpty())
allnewWiki.addAll(newWiki);
else{
for(SeMo_WikiArticle nn : newWiki){
boolean allreadyIn = false;
for(SeMo_WikiArticle oo : allnewWiki){
if(nn.getID()==oo.getID())
allreadyIn= true;
}
if(!allreadyIn)
allnewWiki.add(nn);
}
}
}
Any Ideas?
Add an override function of equals() into class SeMo_WikiArticle :
class SeMo_WikiArticle {
// assuming this class has two properties below
int id;
String name;
SeMo_WikiArticle(int id, String name) {
this.id = id;
this.name = name;
}
#Override
public boolean equals(Object obj) {
// implement your own comparison policy
// here is an example
if (obj instanceof SeMo_WikiArticle) {
SeMo_WikiArticle sw = (SeMo_WikiArticle)obj;
if (this.id == sw.id && (this.name == sw.name || this.name.equals(sw.name))) {
return true;
}
}
return false;
}
}
After that you can use contains() to judge if the list has already contains the specific object of SeMo_WikiArticle.
Here is the code:
private void addPartial(List<SeMo_WikiArticle> allnewWiki, List<SeMo_WikiArticle> newWiki) {
for (SeMo_WikiArticle sw : newWiki) {
if (!allnewWiki.contains(sw)) {
allnewWiki.add(sw);
}
}
}

ChoiceBox with custom Item in a TableView

I have a
private TableView<Indicators> tableviewIndicators;
with column
private TableColumn<Indicators, WindowsItem> tablecolumnFrame;
public static class WindowsItem {
CustomInternalWindow chrt;
private WindowsItem(CustomInternalWindow _chrt) {
chrt = _chrt;
}
public String toString() {
return chrt.getTitle();
}
}
private Indicators(String tl, WindowsItem chrt, String pne, Boolean sel) {
this.tool_col = new SimpleStringProperty(tl);
if (chrt == null) {
this.chart_col = new SimpleStringProperty("");
} else {
this.chart_col = new SimpleStringProperty(chrt.toString());
}
this.pane_col = new SimpleStringProperty(pne);
this.on_col = new SimpleBooleanProperty(sel);
this.chrt = chrt;
}
public String getTool() {
return tool_col.get();
}
public void setTool(String tl) {
tool_col.set(tl);
}
public WindowsItem getChart() {
return chrt;
}
public void setChart(WindowsItem _chrt) {
System.out.println("Indicators::setChart "+chrt.toString());
chrt = _chrt;
}
public String getPane() {
return pane_col.get();
}
public void setPane(String pne) {
pane_col.set(pne);
}
public Boolean getOn() {
return on_col.get();
}
public void setOn(boolean sel) {
on_col.set(sel);
}
public SimpleBooleanProperty onProperty() {
return on_col;
}
public SimpleStringProperty toolProperty() {
return tool_col;
}
public SimpleStringProperty chartProperty() {
return chart_col;
}
public SimpleStringProperty paneProperty() {
return pane_col;
}
}
tablecolumnFrame.setCellValueFactory(new PropertyValueFactory<Indicators, WindowsItem>("chart"));
How can I add a combobox or choicebox in tablecolumnFrame?
The following code
tablecolumnFrame.setCellFactory(new Callback<TableColumn<Indicators, WindowsItem>, TableCell<Indicators, WindowsItem>>() {
#Override
public TableCell<Indicators, WindowsItem> call(TableColumn<Indicators, WindowsItem> param) {
TableCell<Indicators, WindowsItem> cell = new TableCell<Indicators, WindowsItem>() {
#Override
public void updateItem(WindowsItem item, boolean empty) {
super.updateItem(item, empty);
if(empty){
return;
}
if (item != null) {
//final ChoiceBox<WindowsItem> choice = new ChoiceBox<>();
final ComboBox<WindowsItem> choice = new ComboBox<>();
int itemsInTab = chartsInTab.getChildren().size();// dimensione del contenuto del tab, compreso il pane
CustomInternalWindow winItem;
//
for (int i = 0; i < itemsInTab; i++) {
if (chartsInTab.getChildren().get(i) instanceof CustomInternalWindow) {
winItem = (CustomInternalWindow) chartsInTab.getChildren().get(i);
choice.getItems().add(new WindowsItem(winItem));
//choice.getItems().add(winItem.toString());
System.out.println("winItem.toString() "+winItem.toString());
}
}
return this error
SEVERE: javafx.scene.control.Control loadSkinClass Failed to load skin 'StringProperty [bean: TableRow[id=null, styleClass=cell indexed-cell table-row-cell], name: skinClassName, value: com.sun.javafx.scene.control.skin.TableRowSkin]' for control TableRow[id=null, styleClass=cell indexed-cell table-row-cell]
Why do you need special property? You can create ListView with ComboBox quite easily:
ObservableList<WindowsItem> windowsItems = FXCollections.observableArrayList();
ObservableList<WindowsItem> data = FXCollections.observableArrayList();
final ListView<WindowsItem> listView = new ListView<>(data);
listView.setEditable(true);
listView.setItems(data);
listView.setCellFactory(ComboBoxListCell.forListView(windowsItems));