使嵌套的if语句在scala中更具功能性

Pat*_*rty 2 scala

只是想知道是否有人知道如何使以下if语句更具功能性:

val value1 = 8
val value2 = 10


if(val1 > val2){
  println("\n" + stock1 + " has the highest current value")
}else if(val1 < val2){
  println("\n" + stock2 + " has the highest current value")
}else if(val1 == val2)){
  println("\nThe current value for " + stock1 + " is equal the current value for " + stock2)
}
Run Code Online (Sandbox Code Playgroud)

如果有人可以提出建议,我将非常感激.

谢谢

Pet*_*ens 5

使用cat-kernel你可以使用Order[Int].comparison:

import cats.kernel.Order
import cats.kernel.instances.int._
import cats.kernel.Comparison._

val message =
  Order[Int].comparison(val1, val2) match {
    case GreaterThan => s"$stock1 has the highest current value"
    case LessThan    => s"$stock2 has the highest current value"
    case EqualTo => 
      s"The current value for $stock1 is equal the current value for $stock2"
  }

println(s"\n$message")
Run Code Online (Sandbox Code Playgroud)