是否有更简洁的方法来编写此方法?优选地,我不需要匹配所有有效类型,而是允许每个具有*方法的Type.另外,有没有办法asInstanceOf[T]在最后不要求?
def expr_neg[T <: AnyVal](value: T): T = value match {
case int: Int => (int * -1).asInstanceOf[T]
case long: Long => (long * -1).asInstanceOf[T]
case float: Float => (float * -1).asInstanceOf[T]
case double: Double => (double * -1).asInstanceOf[T]
}
Run Code Online (Sandbox Code Playgroud) 我试图使我的count变量同步get和私人帮助函数基于其他成员进行设置.多个线程调用每一个setCount()作为deadlineNoteVisible和referencesAvailable变化.
随着synchronized对刚刚setCount()方法,一切都很好,但是当我添加synchronized(this)到get()电话,我得到:
OutOfMemoryError: Failed to allocate a 57993496 byte allocation with 16764448 free bytes and 32MB until OOM
Run Code Online (Sandbox Code Playgroud)
代码(用Kotlin编写):
var count: Int = 0
// Why does adding synchronized here explode?
get() = synchronized(this) { count }
private set
private fun setCount() {
synchronized(this) {
count = 0
if (deadlineNoteVisible) {
count += 1
}
if (referencesAvailable) {
count += 1
} …Run Code Online (Sandbox Code Playgroud) 我正在运行代码:https: //github.com/bkiers/antlr4-csv-demo.我想通过添加以下行来查看词法分析器分析的标记:
System.out.println("Number of tokens: " + tokens.getTokens().size())
Run Code Online (Sandbox Code Playgroud)
到Main.java:
public static void main(String[] args) throws Exception {
// the input source
String source =
"aaa,bbb,ccc" + "\n" +
"\"d,\"\"d\",eee,fff";
// create an instance of the lexer
CSVLexer lexer = new CSVLexer(new ANTLRInputStream(source));
// wrap a token-stream around the lexer
CommonTokenStream tokens = new CommonTokenStream(lexer);
// look at tokens analyzed
System.out.println("Number of tokens: " + tokens.getTokens().size())
// create the parser
CSVParser parser = new CSVParser(tokens);
// invoke the …Run Code Online (Sandbox Code Playgroud) 我有地图的String,以FunctionS的所有细节的是在语言的有效功能.当我向地图添加一个函数时,我需要指定类型(在本例中Int).
var functionMap: Map[String, (Nothing) => Any] = Map[String, (Nothing) => Any]()
functionMap += ("Neg" -> expr_neg[Int])
def expr_neg[T: Numeric](value: T)(implicit n: Numeric[T]): T = {
n.negate(value)
}
Run Code Online (Sandbox Code Playgroud)
相反,我该怎么做:
functionMap += ("Neg" -> expr_neg)
Run Code Online (Sandbox Code Playgroud)
没有,[Int]并在我打电话后添加它:
(unaryFunctionMap.get("abs").get)[Int](-45)
Run Code Online (Sandbox Code Playgroud)