- Scala Programming Projects
- Mikael Valot Nicolas Jorand
- 245字
- 2021-07-23 16:25:13
If...else expression
In Scala, if (condition) ifExpr else if ifExpr2 else elseExpr is an expression, and has a type. If all sub-expressions have a type A, the type of the if ... else expression will be A as well:
scala> def agePeriod(age: Int): String = {
if (age >= 65)
"elderly"
else if (age >= 40 && age < 65)
"middle aged"
else if (age >= 18 && age < 40)
"young adult"
else
"child"
}
agePeriod: (age: Int)String
If sub-expressions have different types, the compiler will infer a common super-type, or widen the type if it is a numeric type:
scala> val ifElseWiden = if (true) 2: Int else 2.0: Double
ifElseWiden: Double = 2.0
scala> val ifElseSupertype = if (true) 2 else "2"
ifElseSupertype: Any = 2
In the first expression present in the preceding code, the first sub-expression is of type Int and the second is of type Double. The type of ifElseWiden is widened to be Double.
In the second expression, the type of ifElseSupertype is Any, which is the common super-type for Int and String.
An if without an else is equivalent to if (condition) ifExpr else (). It is better to always specify the else expression, otherwise, the type of the if/else expression might not be the one we expect:
scala> val ifWithoutElse = if (true) 2
ifWithoutElse: AnyVal = 2
scala> val ifWithoutElseExpanded = if (true) 2: Int else (): Unit
ifWithoutElseExpanded: AnyVal = 2
scala> def sideEffectingFunction(): Unit = if (true) println("hello world")
sideEffectingFunction: ()Unit
In the preceding code, the common super-type between Int and Unit is AnyVal. This can be a bit surprising. In most situations, you would want to avoid that.
- EJB 3.1從入門到精通
- SEO 20日
- Hands-On Chatbot Development with Alexa Skills and Amazon Lex
- TCP/IP入門經典(第5版)
- 物聯網關鍵技術及應用
- Drush User’s Guide
- 物聯網時代
- 數字調制解調技術的MATLAB與FPGA實現:Altera/Verilog版(第2版)
- WordPress Web Application Development
- 搶占下一個智能風口:移動物聯網
- 4G小基站系統原理、組網及應用
- React Cookbook
- 物聯網工程導論(第3版)
- 云工廠:開啟中國制造云時代
- 物聯網M2M開發技術:基于無線CPU-Q26XX