我在声明部分函数的类型推断时遇到了一些问题。我在下面尝试了Scalatest代码:
class FunSpecTest extends FunSpec {
describe("Partial Function Test") {
def sum1(a: Int, b: Int): Int = a + b
def sum2 = (a: Int, b: Int) => a + b // type-inference hints shown in Intellij
val sum3 = (a: Int, b: Int) => a + b
describe("Partial Function with 2 params") {
it("add 2") {
val sum1val: Int => Int = sum1(_, 2)
assertResult(3)(sum1val(1))
def sum2def = sum2(_, 2)// compilation error, but type-inference hints shown in Intellij
val sum2val = sum2(_, 2)// compilation error
assertResult(3)(sum2def(1))
assertResult(3)(sum2val(1))
val sum3val: Int => Int = sum3(_, 2)
assertResult(3)(sum3val(1))
val sum3valWithoutType= sum3(_, 2) // compilation error
assertResult(3)(sum3valWithoutType(1))
}
}
}
}
我的intelliJ editor中没有显示任何警告/错误
在我运行测试类之前,有一些编译错误: missing parameter type for expanded function
但是sum2def
和sum2val
在Scala shell without given function type中工作正常
我认为Scala编译器应该能够推断sum2def
和sum2val
的类型,而无需说明函数类型Int => Int
。
我的问题是:
val
和def
在我的理解上表现不同吗? def
显示函数推断类型,而val
没有显示。 谢谢
答案 0 :(得分:0)
回答您的两个问题:
1:例如:Scala unexpectedly not being able to ascertain type for expanded function和Why do I get a "missing parameter for expanded function" in one case and not the other?
3:我相信这确实是IntellIJ的一种实现选择,我对此表示赞同。我不想为我定义的每个String或Int值提供类型提示。我