A5300
A5300

Reputation: 419

Expression of type Int doesn't conform to expected type 0

I have the following piece of code

object Solution {

  def solution(prices: Array[Int]): Int = {
    prices.foldLeft((prices.headOption.getOrElse(0), 0)) { (tuple, price) =>
      (Math.min(tuple._1, price), Math.max(tuple._2, price - tuple._1))
    }._2
  }
}

IntelliJ Idea is highlighting Math.max(tuple._2, price - tuple._1) saying that "Expression of type Int doesn't conform to expected type 0".

IntelliJ IDEA 2019.1.3 (Community Edition), Ubuntu

Scala plugin: v2019.1.9

What I'm doing wrong?

Upvotes: 0

Views: 208

Answers (1)

Valy Dia
Valy Dia

Reputation: 2851

It looks like the inferred type of your foldLeft expression is (Int, 0.type), where 0.type is a literal type because of the 0, in the 2nd position in this tuple (prices.headOption.getOrElse(0), 0).

Do you happen to use scala 2.13? This is the version where this feature has been added.

On my machine, IntelliJ highlight the code, with the same error as you, but I can still run the code, therefore I'd say it's a bug on intelliJ where the type is inferred to narrowly.

The other expression Math.min(tuple._1, price) doesn't have that error, because the first element of the resulting tuple of the foldLeft is inferred to Int (because of the expression prices.headOption.getOrElse(0)).

If you do want to get rid of the IntelliJ error message you can use a type ascription:

def solution(prices: Array[Int]): Int = {
    prices.foldLeft[(Int, Int)]((prices.headOption.getOrElse(0), 0)) { (tuple, price) =>
      (Math.min(tuple._1, price), Math.max(tuple._2, price - tuple._1))
    }._2
  }

or

    def solution(prices: Array[Int]): Int = {
      prices.foldLeft((prices.headOption.getOrElse(0), 0: Int)) { (tuple, price) =>
        (Math.min(tuple._1, price), Math.max(tuple._2, price - tuple._1))
      }._2
    }

Upvotes: 2

Related Questions