简体   繁体   中英

How is this type miss match?

HI I am new at Scala Trying to run this code:

 class Number(x : Int){
        var number = x

        def inc(): Int = {
            number => number + 1
        }
  }

But I get the following error: solution.scala:12: error: missing parameter type number => number + 1 I dont know how to fix this.

Essentially, you can expicitly say what type you're expect:

def inc(): Int = {
            number: Int => number + 1
}

BUT this won't compile, cause what you've defined is function, so:

def inc(): (Int) => Int = {
  // some function that takes Int, calls it `number` and increment   
  number: Int => number + 1
}

would be closer,
BUT
it doesn't make sense and notice, that number you've defined has nothing in common with number variable inside class -- that's why Scala compiler cannot infer type for you.

I think you have wanted to write something like:

    def inc(): Int = {number += 1; number;}
    // will take effect on number field

or

    def inc(num: Int): Int = num + 1

or simply:

def inc = (x: Int) => x + 1

since Int return type is inferred, no need to specify it

As for dealing with mutability in the question, inc(1), inc(5), etc. are themselves transformed representations of the number passed to the class instance (ie they equate to "var number", but immutably so). No real need for mutability based on what we see here...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM