Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - value < is not a member of AnyVal

Here is my code. I got a compile error at second case clause:

Error:(92, 26) value < is not a member of AnyVal case x if x._2 < 2 => "price under 2"

def tupleMatch: Unit = {
  val donut = Tuple2("Donut", 2.5)
  val plain = Tuple2("Plain", 1.0)
  val tuples = List(donut, plain)
  tuples.foreach { tuple => 
    val toPrint = tuple match {
      case ("Donut", price) => s"price of Donut is ${donut._2}"
      case (_, price) if price < 2 => "price under 2"
      case _ => "other"
    }
    println(toPrint)

  }
}

After I change

val plain = Tuple2("Plain", 1)

to

val plain = Tuple2("Plain", 1.0)

it finally works. It makes me confusing, I want to know why?

like image 463
Felix J Avatar asked Nov 16 '18 09:11

Felix J


1 Answers

That is because your tuples array is formed by two different types: Tuple2[String, Int] and Tuple2[String, Double]. These types are inferred by the compiler and the interfered type of tuples array is then Tuple2[String, AnyVal]. When you put a Double representation the compiler is capable of create the Tuple2[String, Double].

like image 152
Emiliano Martinez Avatar answered Sep 24 '22 00:09

Emiliano Martinez