0
votes

I got some problems about the type inference for declaring a partial function. I tried the Scalatest code below:

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))
            }
        }

    }
}

there is no any warning/error shown in my intelliJ editor

Until I run the test class and there are some compilation error: missing parameter type for expanded function

But sum2def and sum2val work fine in Scala shell without given function type

I think Scala compiler should able to infer the type of sum2def and sum2val without stating the function type Int => Int.

My questions are :

  1. Why my intellij editor does not show me the error/warning until I compile the code? Is my code valid in scala syntax? If it is not valid, how to set my intellij to show me the error?
  2. Why my code used in intellij does not compile but works fine in scala shell?
  3. val and def behave different in my intelliJ? def shows the function inferred type while val does not.

Thank you

1
The code as pasted works fine for me in an sbt project with scalatest dependency. Maybe there is something wrong with the project configuration? - Justin Kaeser

1 Answers

0
votes

Answers to 2 of your questions:

1: See for example: Scala unexpectedly not being able to ascertain type for expanded function and Why do I get a "missing parameter for expanded function" in one case and not the other?

3: I believe that this is really a implementation choice by IntellIJ and I kind of approve of it. I would not want to have type hints for each and every String or Int value I define. I