Scala 编译时错误,缺少参数类型

问题描述

我正在尝试使用此代码进行对话以获取数字输入

val dialog: TextInputDialog = new TextInputDialog{
    initOwner(Main.stage)
    title = "Set Programme Counter"
    headerText = "Numeric format not supported."
    contentText = "New PC value:"

    import java.text.DecimalFormat

    val format = new DecimalFormat("#.0")
    import java.text.ParsePosition
    editor.settextformatter(new textformatter( c => {
        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)
    }))
}

但是得到缺少的参数类型编译错误

[error]         editor.settextformatter(new textformatter( c => {
[error]                                                    ^

不知道参数类型应该是什么,尽管谷歌搜索也找不到任何有用的提示

IntelliJ 认为没有任何问题,但 sbt 在编译时给出了错误

解决方法

constructor being used 是 UnaryOperator 类型,因此 TextFormatter.Change => TextFormatter.Change 类型应该是兼容的。

使用 Scala 2.12 REPL,这将起作用(使用带有 UnaryOperator 的上述构造函数签名):

import javafx.scene.control.TextFormatter
val tf = new TextFormatter((c: TextFormatter.Change) => c)

如果编译器无法推断构造函数的匹配类型,则可能会发生丢失类型错误,如果导入不正确,甚至可能是旧版本的 Scala 与正在使用的版本不匹配,则可能会发生这种情况你的 IDE。

既然你说IntelliJ没有发现问题,那么看来后者的可能性更大。请检查您的 IDE 中的项目设置是否与 build.sbt 中的 scalaVersion 匹配。

您可能还想通过显式定义某些术语来减少必须由编译器完成的推理。例如,您可以尝试显式定义 UnaryOperator:

import java.util.function._
val uo: UnaryOperator[TextFormatter.Change] = UnaryOperator.identity[TextFormatter.Change]()
val tf = new TextFormatter(uo)