2016-12-02 5 views
2

でネストされたif文は、より機能的な作り:誰かが提案を作ることができれば誰もが声明より機能場合は、次のようにする方法を知っているかどう思っScalaの

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) 
} 

私は非常に感謝されます。

おかげ

+1

「より機能的」とは何ですか? – maasg

答えて

2

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) 
} 
+0

ありがとう、それはトリックを行います。 –

1

またはこの:

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

あなたが使用することができcats-kernelOrder[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") 
1

このように?あなたのソリューションについて十分に機能していないと思いますか?

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" 
) 
2

ここで機能的であることの重要な点は、効果と計算を区別することです。

あなたのスニペットは、印刷するメッセージと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 
関連する問題