【发布时间】:2019-04-01 05:44:48
【问题描述】:
我在声明偏函数的类型推断方面遇到了一些问题。我尝试了下面的 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。
我的问题是:
- 为什么我的 intellij 编辑器在我编译代码之前不显示错误/警告?我的代码在 scala 语法中有效吗?如果它无效,如何设置我的 intellij 以显示错误?
- 为什么我在 intellij 中使用的代码无法编译但在 scala shell 中运行良好?
-
val和def在我的 intelliJ 中表现不同?def显示函数推断类型,而val不显示。
谢谢
【问题讨论】:
-
粘贴的代码在具有 scalatest 依赖项的 sbt 项目中对我来说很好。可能是项目配置有问题?
标签: scala intellij-idea type-inference scalatest