Hey guys i am trying to pass an Object(type Object) that is a combination of a (string+object).
In the function i need to compare the the string with a hash map and accordingly do operations with the attached object.
The code goes like this
Function (srt : Object)
{
//s is an array of Strings
var s = srt.toString.split("+")
if(s[0]== insert)
{
var ne = s[1].asInstanceOf(USERDEFINEDCLASS) //ERROR here
//do operations
}
}
main()
{
var og : className = new className(parameters)
Function(og ->("insert"))
}
In this code i am getting the error saying it cannot be converted from string to the class object.
I am not able to figure out a way of doing it. Can someone help me with this
I am not sure it will help you. Here follows a program with some features you described:
class Main{
class SomeClass(val x:String) { override def toString:String = x }
def funct(obj:Object) {
val s=obj.toString.split("+")
if(s(0) == "a" ) { // assumingn it's a non empty string
println(obj.asInstanceOf[SomeClass].x)
}
}
def main(args:Array[String]):Unit = {
funct(new SomeClass("a+b"))
}
}
Related
I have a bit of code which is used in both functions, but the code which I want to move to separate function has a return statement, how can I achieve this
private fun handleFlingCompleteFailure(failure: Failure) {
Timber.d("Failure caught when using fling complete $failure")
val order = orderStorage.fOrder ?: return // 1 - move
val currentStatus: String = order.status // 2 - move
val logTimed = LogMapTimed("Acraft Flling Complete (partial: $view?.isPartiallyComplete)")
fllingCompleteUseCaseError(logTimed, "$failure", currentStatus)
}
private fun handleFllingCompleteSuccess(response: FlOrderCompleteResponse) {
val logTimed = LogMapTimed("Acraft Flling Complete (partial: $view?.partiallyComplete)")
val order = orderStorage.flOrder ?: return //1 - move
val currentStatus: String = order.status. //2 - move
if (response.success) {
fllingCompleteResponse(response, order, logTimed, currentStatus)
} else {
fllingCompleteUseCaseError(logTimed, "response - $response.success", currentStatus)
}
}
what I want to do is
private fun getCurrentOrderStatus(): String {
val order = orderStorage.flOrder ?: return
val currentStatus: String = order.status
return currentStatus
}
but how can I manage the return statement for the order
please suggest how can I do this
thanks
R
You can return Nullable String from extracted method:
private fun getCurrentOrderStatus(): String? {
val order = orderStorage.flOrder ?: return null
val currentStatus: String = order.status
return currentStatus
}
And use elvis operator to fast return from client function:
private fun handleFlingCompleteFailure(failure: Failure) {
Timber.d("Failure caught when using fling complete $failure")
val currentStatus: String = getCurrentOrderStatus() ?: return
// all other
If you create a new function, it has no control over the flow of the function that called it, so it can't force the caller to return. The caller has to manage that itself, by checking the result and deciding whether to return early.
Your other problem is that you want to return two values, because if your calling function doesn't return early, it has some work to do, and it needs multiple variables to do it.
Here's a couple of approaches you could take, if you want to do this:
First up, you can create a result type, which either gives you both pieces of data, or an error type (or just null, which is what I'm gonna do)
data class OrderData(val order: SomeType, val currentStatus: String)
private fun getCurrentOrderStatus(): OrderData? {
// this could be an expression instead of using return
return orderStorage.flOrder?.let { OrderData(it, it.flOrder) }
}
Then you can use it in your calling function
private fun handleFllingCompleteSuccess(response: FlOrderCompleteResponse) {
val logTimed = LogMapTimed("Acraft Flling Complete (partial: $view?.partiallyComplete)")
val orderData = getCurrentOrderStatus()
// early return - do it however you like, use a let block if you want
if (orderData == null) return
// smart casting means if it isn't null, it's definitely an OrderData with all the values
if (response.success) {
fllingCompleteResponse(response, orderData.order, logTimed, orderData.currentStatus)
} else {
fllingCompleteUseCaseError(logTimed, "response - $response.success", orderData.currentStatus)
}
}
That's still requiring you to handle the early return yourself, but honestly that's logic the caller should be handling itself - what to do if the data isn't available
Another approach you could take is the functional one, pass in a function to invoke if the data is available.
private fun getCurrentOrderStatus(onSuccess: (WhateverFlOrderIs, String) -> Unit) {
// same as before, except we're extracting the data and calling
// the passed function with it - if flOrder is null we do nothing
orderStorage.flOrder?.let { onSuccess(it, it.currentStatus) }
}
Now you can do this instead:
private fun handleFllingCompleteSuccess(response: FlOrderCompleteResponse) {
val logTimed = LogMapTimed("Acraft Flling Complete (partial: $view?.partiallyComplete)")
getCurrentOrderStatus() { order, currentStatus ->
if (response.success) {
fllingCompleteResponse(response, order, logTimed, currentStatus)
} else {
fllingCompleteUseCaseError(logTimed, "response - $response.success", currentStatus)
}
}
}
This way, your getCurrentOrderStatus function returns nothing anyway, so there's nothing to check and no early returning to do. Your caller just invokes it, passes it a function to run if it can, and that's the end of the method anyway.
I am writing test method like setTask(Task task). And Task object has several fields, e.g.
public String vehicle;
Method setTask should be used in different test-cases, so I'd like to have an options for this field to accept values:
null - the method should not do anything in this particulare case;
some string value - e.g. "", "Hello, World!", "Iso Isetta", ...
random - a value that indicates (as well as null indicates "no changes") that a random value should be selected for a drop-down list corresponding to this field.
So what can I do to make String to be SpecialString which could accept values null, random & some string value? (BTW: I don't want to set it to string value "RANDOM", and chech whether the value is equal to "RANDOM"-string)
UPDATE: I don't mean random like random value from a set of values, I mean random as well as null and this is for setTask() to handle random (select random from drop-down), and not to pass a random string from a set of values.
Pseudocode:
Task task = new Task();
task.vehicle = random; // as well as null
setTask(task)
in setTask(Task task):
if (task.vehicle == null) {
//skip
} else if (task.vehicle == random) {
// get possible values from drop-down list
// select one of them
} else {
// select value from drop-down list which is equal to task.vehicle
}
Don't assign a fixed String but use a Supplier<String> which can generate a String dynamically:
public Supplier<String> vehicleSupplier;
This, you can assign a generator function as you request:
static Supplier<String> nullSupplier () { return () -> null; }
static Supplier<String> fixedValueSupplier (String value) { return () -> value; }
static Supplier<String> randomSupplier (String... values) {
int index = ThreadLocalRandom.current().nextInt(values.length) -1;
return index > 0 && index < values.length ? values[index] : null;
}
In use, this looks like:
task.setVehicleSupplier(nullSupplier()); // or
task.setVehicleSupplier(fixedValueSupplier("value")); // or
task.setVehicleSupplier(randomSupplier("", "Hello, World!", "Iso Isetta"));
and you can get the String by
String value = task.vehicleSupplier().get();
or hide the implementation in a getter function
class Task {
// ...
private Supplier<String> vehicleSupplier;
public void setVehicleSupplier(Supplier<String> s) {
vehicleSupplier = s;
}
public String getVehicle() {
return vehicleSupplier != null ? vehicleSupplier.get() : null;
}
// ...
}
What you may want to do is to create an object that wraps a string as well as some information about whether or not it's a special value. Something along the lines of...
public class Special<T> {
public enum Type {
NOTHING, RANDOM, SPECIFIC
}
private final Type type;
private final T specificValue;
public Special(Type type, T specificValue) {
this.type = type;
this.specificValue = specificValue;
}
public Type getType() {
return type;
}
public T getSpecificValue() {
if (type != SPECIFIC) {
throw new IllegalStateException("Value is not specific");
}
return specificValue;
}
}
The class above could be used like so:
Special<String> a = new Special<>(Special.Type.NOTHING, null);
Special<String> b = new Special<>(Special.Type.SPECIFIC, "Hello");
if (b.getType() == Special.Type.RANDOM) {
// do something
}else if (b.getType() == Special.Type.SPECIFIC) {
String val = b.getSpecificValue();
// do something else
}
A slightly more polished variant of the thing above is probably the best way, but there is a way, a much uglier way, to do it using nothing but a String field.
What you could do is to have a "magical" string instance that behaves differently from all other string instances, despite having the same value. This would be done by having something like
static final String SPECIAL_VALUE_RANDOM = new String("random");
Note the use of the String constructor, which ensures that the string becomes a unique, non-interned instance. You can then say if (vehicle == SPECIAL_VALUE_RANDOM) { ... } (note the use of == instead of .equals()) to check if that specific instance (rather than any other string that says "random") was used.
Again, this is not a particularly good way of doing this, especially if you intend to do this more than once ever. I would strongly suggest something closer to the first way.
I am working on a pre-existing java program, one of its classes calculates some Boolean features. Some private methods do this. Their return type is Predicate. For example :
private Predicate<ChunkedBinaryExtraction> startArg1() {
return new Predicate<ChunkedBinaryExtraction>() {
public boolean apply(ChunkedBinaryExtraction e) {
return e.getArgument1().getRange().getStart() == 0;
}
};
}
I want to retrieve this feature value, I used this simple statements:
Predicate<ChunkedBinaryExtraction> ftr1=startArg1();
System.out.print("Feature1 is: "+ftr1);
The result should return a Boolean value :true or false, but it shows:
Feature1 is: edu.washington.cs.knowitall.extractor.conf.ReVerbFeatures$3#1eb44e46
I'm new to Java programming, please help:( Thanks.
You are returning an object. So the print will call toString() on the predicate object. I guess you want the result of the apply method, so you need to do sth. like this
ChunkedBinaryExtraction someObject = ...
Predicate<ChunkedBinaryExtraction> ftr1 = startArg1();
System.out.print("Feature1 is: " + ftr1.apply(someObject));
Where the ChunkedBinaryExtraction object comes from, you have to know.
I am busy with a project that extracts data from a xml file and displays it in a word document. I have created a method for this extraction, but I want to simplify it by using an array of methods.
This is just an example of how I test for certain information at the moment:
for (int i = 0; i < nodeMap.getLength(); i++) {
Node node = nodeMap.item(i);
if (node.getNodeName().equalsIgnoreCase("maximumRedeliveries")) {
if (node.getNodeValue().startsWith("{{")) {
retryLogic.setMaximumRedeliveries(extractPropertyName(node.getNodeValue(), propFileLocation));
} else {
retryLogic.setMaximumRedeliveries(node.getNodeValue());
}
}
if (node.getNodeName().equalsIgnoreCase("asyncDelayedRedelivery")) {
if (node.getNodeValue().startsWith("{{")) {
retryLogic.setAsyncDelayedRedelivery(extractPropertyName(node.getNodeValue(), propFileLocation));
} else {
retryLogic.setAsyncDelayedRedelivery(node.getNodeValue());
}
}
}
I am aiming to create an array for the if statement values, for example "maximumRedeliveries" and "asyncDelayedRedelivery" and an array for their corresponding methods, for example setMaximumRedeliveries(),setAsyncDelayedRedelivery(). I am unsure of how to create an array of methods, or if it's even possible?
This problem differs form Java - Creating an array of methods, because I use set methods and don't know how to implement it in that way.
First, ensure that extractPropertyName takes names with and without curly braces, and behaves like this:
String extractOptionalPropertyName(String name, String propFileLocation) {
return name..startsWith("{{") ? extractPropertyName(name, propFileLocation) : name;
}
This moves conditionals from your XML processing code into a helper:
String nodeName = node.getNodeName();
if (nodeName.equalsIgnoreCase("maximumRedeliveries")) {
retryLogic.setMaximumRedeliveries(extractOptionalPropertyName(node.getNodeValue(), propFileLocation));
} else if (nodeName.equalsIgnoreCase("asyncDelayedRedelivery")) {
retryLogic.setAsyncDelayedRedelivery(extractOptionalPropertyName(node.getNodeValue(), propFileLocation));
} ... // and so on
With these changes in place, you can follow the recipe from this other Q&A and make a Map<String,ValSetter> objects, like this:
interface ValSetter {
void set(RetryLogic logic, String val);
}
// The map can be made static in a class
Map<String,ValSetter> setterForName = new HashMap<>();
{ // Initializer block
setterForName.put("maximumredeliveries", new ValSetter() {public void set(RetryLogic logic, String val) { logic.setMaximumRedeliveries(val);}} );
setterForName.put("asyncrelayedredelivery", new ValSetter() {public void set(RetryLogic logic, String val) { logic.setAsyncDelayedRedelivery(val);}} );
}
Now your XML handler could look like this:
String nodeName = node.getNodeName();
ValSetter setter = setterForName.get(nodeName.toLowerCase());
if (setter != null) {
String val = extractOptionalPropertyName(node.getNodeValue(), propFileLocation);
setter.set(retryLogic, val);
} else {
// report an error
}
I don't think i have the terminology correct, haven't been one for that. What i'm trying to do is get a string back , then use it to run functions. .. Example :
int slotNumber = ((j*3)+i+1);
String slotString = "slot"+slotNumber;
Regularly I can do this :
slot12.Draw();
And I want to be able to do this :
slotString.Draw();
With it substituting slotString with slot12 in a dynamic scenario. If i truly have to i could do something similar to :
if (slotString == slot1) slot1.Draw();
if (slotString == slot2) slot2.Draw();
And such, but i dont really want to use x number of lines for x number of slots.
Any help is appreciated :D
A possible solution would be to use a HashMap where the key is the slotNumber and the value points to the slot. Then you could do something like the following.
//Initialize at the start of your program
HashMap<int, Slot> SlotHash = new HashMap<int, Slot>();
//Code to retrieve slot and call Draw().
Slot select = SlotHash.get(slotNumber);
select.Draw();
Maybe use a Map if your slots are sparsely-packed. If they're densely-packed, you might be able to use an array of slots. In either case, you do the slot lookup based on index and then call Draw on the looked-up slot.
You would have something like this:
Slot slot1 = new Slot("slot1");
Slot slot2 = new Slot("slot2");
SlotController controller = new SlotController();
controller.add(slot1);controller.add(slot2);
String someSlotNumber = ".....";
controller.draw(someSlotNumber);
See the definition of the classes below:
class SlotController {
Map<String, Slot> slotMap = new HashMap<String, Slot>();
public void addSlot(Slot aSlot) {
slotMap.put(aSlot.getSlotName(), aSlot);
}
public void draw(String slotName) {
slotMap.get(slotName).draw();
}
}
class Slot {
private String slotName;
public Slot(String name){
slotName = name;
}
public String getSlotName() {
return slotName;
}
public void draw() {
}
}