Scala编译报missing parameter type错误,TextFormatter参数类型缺失怎么解决
问题原因
JavaFX的TextFormatter为泛型类,你传入的lambda作为格式化过滤器参数时,Scala编译器无法自动推断lambda入参c的类型。sbt的类型检查规则比IntelliJ内置代码检查更严格,因此会抛出missing parameter type错误,而IntelliJ不会识别到该问题。
解决方案
给lambda的入参c显式声明类型即可解决问题,必要时可同时显式指定TextFormatter的泛型参数,修改后的代码如下:
editor.setTextFormatter(new TextFormatter[String]( (c: TextFormatter.Change) => { def foo(c:TextFormatter.Change): TextFormatter.Change = { if (c.getControlNewText.isEmpty) return c val parsePosition = new ParsePosition(0) val o = format.parse(c.getControlNewText, parsePosition) if (o == null || parsePosition.getIndex < c.getControlNewText.length) null else c } foo(c) }))
如果没有其他复用需求,也可以简化掉内部的foo函数,直接将校验逻辑写在lambda中:
editor.setTextFormatter(new TextFormatter[String]( (c: TextFormatter.Change) => { if (c.getControlNewText.isEmpty) return c val parsePosition = new ParsePosition(0) val o = format.parse(c.getControlNewText, parsePosition) if (o == null || parsePosition.getIndex < c.getControlNewText.length) null else c }))
内容的提问来源于stack exchange,提问作者Ian
相关产品推荐
相关产品推荐

