我在声明分部函数的类型推断方面遇到了一些问题。我尝试了下面的 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))
}
}
}
}
我的智能编辑器中没有显示任何警告/错误
直到我运行测试类并且出现一些编译错误:缺少扩展函数的参数类型
但是sum2def
和sum2val
在没有给定函数类型的 Scala shell 中工作正常
我认为 Scala 编译器应该能够在不说明函数类型Int => Int
的情况下推断出sum2def
和sum2val
的类型。
我的问题是:
- 为什么我的 intellij 编辑器在编译代码之前没有向我显示错误/警告?我的代码在 scala 语法中有效吗?如果它无效,如何设置我的智能以显示错误?
- 为什么我在 intellij 中使用的代码不能编译,但在 scala shell 中工作正常?
-
val
和def
在我的智能中表现得不同吗?def
显示函数推断类型,而val
则不显示。
谢谢
您的 2 个问题:
1:例如:Scala 意外无法确定扩展函数的类型以及为什么我在一种情况下得到"扩展函数缺少参数"而不是另一种情况?
3:我相信这确实是IntellIJ的实现选择,我有点赞同它。我不想为我定义的每个字符串或 Int 值提供类型提示。我