繁体   English   中英

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

[英]Making a nested if statement more functional in 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)
}

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

谢谢

使用cats-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")

match ,如果你喜欢它

val1 match{
  case v if v > val2 => println("\n" + stock1 + " has the highest current value")
  case v if v < val2 => println("\n" + stock2 + " has the highest current value")
  case _ => println("\nThe current value for " + stock1 + " is equal the current value for " + stock2)
 } 

我认为在这里运作的关键是将计算与效果分开。

您的代码段正在计算要打印和执行IO的消息。 使用if语句没有任何问题 - 在这种情况下,我会说这是编写它的最清晰的方法。

val value1 = 8
val value2 = 10

def valueMessage =
  if (val1 > val2) stock1 + " has the highest current value"
  else if (val1 < val2) stock2 + " has the highest current value"
  else "The current value for " + stock1 + " is equal the current value for " + stock2

def printValueMessage() = println("\n" + valueMessage)

printValueMessage() // unsafe

或这个:

math.signum(value1 - value2) match {
      case -1 => println("v1 <= v2")
      case 1  => println("v1 >= v2")
      case _  => println("v1 == v2")
    }

像这样? 您认为您的解决方案功能不足?

println(
  if (val1 > val2)
    s"\n$stock1 has the highest current value"
  else if (val1 < val2)
    s"\n$stock2 has the highest current value"
  else 
    s"\nThe current value for $stock1 is equal the current value for $stock2"
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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