Convert OwnLang value to Java object

This commit is contained in:
aNNiMON 2023-11-09 19:53:47 +02:00 committed by Victor Melnik
parent 5d00598e8c
commit 523c76dd38
4 changed files with 24 additions and 8 deletions

View File

@ -2,9 +2,7 @@ package com.annimon.ownlang.lib;
import com.annimon.ownlang.exceptions.ArgumentsMismatchException; import com.annimon.ownlang.exceptions.ArgumentsMismatchException;
import com.annimon.ownlang.exceptions.TypeException; import com.annimon.ownlang.exceptions.TypeException;
import java.util.Arrays; import java.util.*;
import java.util.Iterator;
import java.util.List;
/** /**
* Represents array type. * Represents array type.
@ -131,6 +129,11 @@ public class ArrayValue implements Value, Iterable<Value> {
return elements; return elements;
} }
@Override
public Object asJavaObject() {
return Arrays.stream(elements).map(Value::asJavaObject).toArray(Object[]::new);
}
@Override @Override
public int asInt() { public int asInt() {
throw new TypeException("Cannot cast array to integer"); throw new TypeException("Cannot cast array to integer");

View File

@ -69,6 +69,11 @@ public class ClassInstance implements Value {
return thisMap; return thisMap;
} }
@Override
public Object asJavaObject() {
return thisMap.asJavaObject();
}
@Override @Override
public int asInt() { public int asInt() {
throw new TypeException("Cannot cast class " + className + " to integer"); throw new TypeException("Cannot cast class " + className + " to integer");

View File

@ -1,10 +1,7 @@
package com.annimon.ownlang.lib; package com.annimon.ownlang.lib;
import com.annimon.ownlang.exceptions.TypeException; import com.annimon.ownlang.exceptions.TypeException;
import java.util.Iterator; import java.util.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer; import java.util.function.Consumer;
/** /**
@ -94,6 +91,13 @@ public class MapValue implements Value, Iterable<Map.Entry<Value, Value>> {
return map; return map;
} }
@Override
public Object asJavaObject() {
Map<Object, Object> result = new HashMap<>(map.size());
map.forEach((k, v) -> result.put(k.asJavaObject(), v.asJavaObject()));
return result;
}
@Override @Override
public int asInt() { public int asInt() {
throw new TypeException("Cannot cast map to integer"); throw new TypeException("Cannot cast map to integer");

View File

@ -15,4 +15,8 @@ public interface Value extends Comparable<Value> {
String asString(); String asString();
int type(); int type();
default Object asJavaObject() {
return raw();
}
} }