Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Saturday, May 26, 2012

Using named and default arguments

This time I inlined some comments in REPL output just in case you wondered how that got there.
scala> def orderBigMacMenu(drink: String = "Coke", withMayo: Boolean = true): String = {
     |    /** the meal gets prepared **/
     |    "You ordered BigMac menu with " + drink + (if (withMayo) " with " else " without ") + "mayonaise"
     | }
orderBigMacMenu: (drink: String, withMayo: Boolean)String

scala>

scala>

scala> orderBigMacMenu("drinkA", false)
res4: String = You ordered BigMac menu with drinkA without mayonaise

scala> orderBigMacMenu("drinkB", true)
res5: String = You ordered BigMac menu with drinkB with mayonaise

/** code below works because compiler tries to use arguments provided from left to right 
and "drinkc" is of type String **/
scala> orderBigMacMenu("drinkC")
res6: String = You ordered BigMac menu with drinkC with mayonaise

/** code below fails because compiler tries to use arguments provided from left to right 
and "true" is of type Boolean **/
scala> orderBigMacMenu(true)
:9: error: type mismatch;
 found   : Boolean(true)
 required: String
Error occurred in an application involving default arguments.
              orderBigMacMenu(true)

/** When using named arguments, there is no issue. You can even swap them around if you want to. **/
scala> orderBigMacMenu(withMayo=false)
res8: String = You ordered BigMac menu with Coke without mayonaise

scala> orderBigMacMenu(withMayo=false, drink="Beer")
res9: String = You ordered BigMac menu with Beer without mayonaise

No comments:

Post a Comment