语法级别
- try-catch-finally
try {
} catch {
}
// 处理所有类型错误(Error)
try {
} catch (err) {
} finally {
}
// todo: 是否需要多级catch
try {
} catch (e : DivZeroError) {
} catch (e : ParseNumberError) {
} catch (e : Error) {
} finally {
}
// 只处理指定类型的错误
try {
} catch (e : DivZeroError) {
} finally {
}
- instanceof / is
val cat = new Cat();
if (cat instanceof Tiger) {
// xxx
}
val v1 = nil;
val b = v1 instanceof Cat; // false
val b2 = v1 is Cat; // false
- switch
switch (value) {
case constVal1: {
break;
}
case constVal2: {
return;
}
default: {
}
}
// todo:高级switch??
val v1 = switch (value) {
case constVal1: "text"->length();
case constVal2: 2;
default: callSomeFunc();
}
- import for
import com.southstate.FileUtils for { listFiles as getFiles, listDirs }; // listFiles和listDirs必须是静态方法
class MyClass {
public MyClass() {
val utils = new FileUtils();
val bEq = utils->listFiles == getFiles; // true
}
}
- 结构话字符串
`我爱${name}已经${years}年了`
Annotations 一个参数都不写会默认有一个value
export @interface Path {
val value;
val name = 'jerry';
}
Iterable / Iterator
- 所有可foreach迭代对象都必须继承Iterable接口
class ChildrenIterator implements Iterator {
public ChildrenIterator() {
// xxx
}
public val hasNext() {
// return xxx;
}
public val next() {
// return xxx;
}
}
export class Children implements Iterable {
public val getIndex(index) {
// xxx
}
public void setIndex(index, value) {
// xxx
}
public val keyIterator() {
return new ChildrenIterator();
}
}
String
Array
- 构造
val arr;
arr = new Array(10, 'text'); // 10个 'text'
arr = new Array(100); // 100个 nil
arr = new Array(); // 空的
arr = [0, 1, ['text'], { children: [] }, 'text'];
- for / foreach
val arr = new Array(10, nil);
for (val i = 0; i < arr->length(); i += 1) {
Console->print(i); // 10个nil
}
val arr = [1, 2, 3];
foreach (val index, value in arr) {
Console->print(index); // 0 1 2
Console->print(value); // 1 2 3
}
- length
- add
- remove
- insert
- replace
- join
- map
- forEach
- filter
- matchOne
- matchAll
- find
- findLast
- findIndex
- findLastIndex
- sort
- indexOf
- lastIndexOf
- reverse
- reduce
- [index] / getIndex(index)
- ImmutableArray 不可更改数组
Range
- 构造
val r = [0...5]; // 0,1,2,3,4
val r = [0...5, 2]; // 0 2 4
val start = 0;
val r = [start...(10 + start), 3]; // 0 3 6 9
[0...5, 2]->length(); // 3
r->length(); // 3
- for / foreach
val arr = [0...5, 2]->toArray(); // [0, 2, 4]
foreach (val i, v in [0...10, 2]) {
Console->print(i); // 0 1 2 3 4
Console->print(v); // 0 2 4 6 8
}
- 不能更新,构建后即为死值
- length
- map
- forEach
- reverse
- reduce
- toArray
- [index] / getIndex(index)
Table
- 有序keys??
- 构造
val table1 = new Table();
val table2 = {};
val children = [];
val user = {
name: 'Tom',
'the-age': 23,
male: false,
children,
goWalk: () => 'xxx'
};
- keys
- hasKey
val tbl = {
name: '张三',
weight: nil
};
// true
val b = tbl->hasKey('name');
// true
val b = tbl->hasKey('weight');
// true
val b = !!tbl.name;
// false
val b = !!tbl.weight;
- values
- clear
- removeKey
- forEach
- [key] / getIndex(key)
- toArray
Errors
- TypeError
- DivZeroError
- RangeError
- SyntaxError
- ParseError
- TargetError
- Error
Reflect
-
classOf 获取对象或类型的Class描述
val clazz = Reflect->classOf(UserModel);
-
expands 静态方法,扩展Object的原始功能
- expands(object, toExpandMethods, tagValue)
-
expands(object, toExpandMethods)
// tagValue nil
用法 val object2 = Reflect->expands(object, toExpandMethods, tagValue);
object
是原始对象,不能是基础类型(boolean, integer, float, nil, function),toExpandMethods
是一个Table
,不能为nil,每个key-value
是函数(如getAge
),会为object
生成同名扩展函数,使用object
调用这个名称(getAge
)时候,会映射到扩展函数(getAge
)。tagValue
是标签对象,供扩展函数使用。本函数返回object
。
扩展函数如下,getAge
是函数名称,函数回调传参分别是:ref
是object
,tag
是最初传入的tagValue
,
val toExpandMethods = {
getAge: (ref, tag, arg1, [...argN]) => {
// xxx
}
};
例子:
val arr = [1, 2, 3, 4, 5];
val toExpandMethods = {
reverseJoin: (ref, tag, gapStr) => {
return ref->reverse()->join(gapStr);
}
};
val tagValue = nil;
Reflect->expands(arr, toExpandMethods, tagValue);
val str = arr->reverseJoin('-'); // 5-4-3-2-1
- expandsNew 等价于调用new对象,然后调用expandObject
val toExpanded = {
reverseJoin: (ref, gapStr) => {
return ref->reverse()->join(gapStr);
}
};
val args = [[1, 2, 3, 4, 5]];
val arr = Reflect->expandsNew(Array, toExpanded, tagV, args);
val str = arr->reverseJoin('-'); // 5-4-3-2-1
- newProxy 为接口类型创建代理对象
interface HttpApi {
@HttpGet('/user/${id}')
val getUserById(@Path('id') id);
}
class HttpRequest {
private val callback;
public void setCallback(callback) {
this->callback = callback;
}
}
val httpConfig = {
base: 'https://smu.com/',
httpGet: (url) => {
val req = new HttpRequest();
// do real http get
// req->callback(response);
return req;
}
};
val httpProxy = Reflect->newProxy(HttpApi, (ref, tag, method, args) => {
log('call before');
val path = method->annotations[0]->value;
foreach (val i, argAnnos in method->argsAnnotations) {
foreach (val j, argAnno in argAnnos) {
if (argAnno is Path) {
val pathVar = '${' + argAnno->value + '}';
path = path->replace(pathVar, args[i]->toString());
break;
}
}
}
val url = tag.base + ;
return tag.httpGet(url); // 发起get请求
log('call after');
}, httpConfig)
val req = httpProxy->getUserById(101);
req->setCallback((response) => {
// xxx
});
Class 类型的描述信息
package a.b;
class UserModel {
private val name;
public final val gender;
public val getName() {
return name;
}
}
val clazz = Reflect->classOf(UserModel);
clazz->shortName; // UserModel
clazz->name; // a.b.UserModel
clazz->targetPublicFields; // 当前类本身的公共属性
clazz->targetFields; // 当前类本身的所有属性,包括私有和保护的
clazz->allPublicFields; // 所有的公共属性,包括继承来的
clazz->allFields; // 所有的属性,包括继承来的和私有保护的
clazz->getPublicField(name); // 获取指定的公共属性
clazz->getField(name); // 获取指定属性
clazz->targetPublicMethods; // 当前类本身的功能函数
clazz->targetMethods; // 当前类本身的所有函数,包括私有保护的
clazz->allPublicMethods; // 所有的公共函数,包括继承来的
clazz->allMethods; // 所有的函数,包括继承来的和私有保护的
clazz->getPublicMethod(name, argCount); // 获取指定函数名称和参数个数的公共函数
clazz->getMethod(name, argCount); // 获取指定函数名称和参数个数的函数
clazz->constructors; //
clazz->getConstructor(argCount); //
val superClazz = clazz->getSuperClass(); //
val myInterfaces = clazz->getTargetInterfaces(); //
val allInterfaces = clazz->getAllInterfaces(); //
Method
name;
argCount;
accessible;
annotations;
argsAnnotations; // val someFunc(@AnnA() @AnnB arg)
invoke(ref, args);s
Field
Promise
async / await
工具类
Math
RegExp
Date
Json
- parse
// 普通类
val user = Json->parse(UserModel, 'json string');
// Table类
val table = Json->parse(Table, 'json string');
// 默认Table类
val table = Json->parse('json string');
// 自定义Table类
val myTable = Json->parse(MyTableClass, 'json string');
- stringify
//
val json = Json->stringify(tableOrObject, includekeys, space);
//
val json = Json->stringify(tableOrObject, includekeys);
//
val json = Json->stringify(tableOrObject);
未完成
- 多继承检查
- poplar.lang下类无需导入??? ✅
- 要不要支持
val type = User; val user = new type('Jerry');
??? ❌ - 去掉
new Error()
的栈占用 - 函数不定参数
System->loadLibrary()
-
[...keys]
解构 -
a is Number; a is Float; a is Integer; a is Object; a is Boolean; a is Function;
基础数据类型