4 ms·
This is one of the features of Scala I like; explicit types for Option/Some/None in the core language and standard API. It's generally used for return types (ex
by sehrope 14y ago
This is one of the features of Scala I like; explicit types for Option/Some/None in the core language and standard API. It's generally used for return types (ex: a hashmap 'get' will have a return type of Option[ValueType] and return either Some[ValueType] or None) but you can use it for function parameters as well.
scala> def foo(name:Option[String] = None, age:Option[Int] = None) = {
| println("==========")
| if( name.isDefined )
| println("Name: " + name.get)
| if( age.isDefined )
| println("Age: " + age.get)
| println("==========")
| }
foo: (name: Option[String], age: Option[Int])Unit
scala> foo()
==========
==========
scala> foo(Some("Alice"))
==========
Name: Alice
==========
scala> foo(age = Some(10))
==========
Age: 10
==========
Plus with some implicit syntactic sugar...
scala> implicit def strToSome(s:String) = Some(s)
strToSome: (s: String)Some[String]
scala> implicit def intToSome(i:Int) = Some(i)
intToSome: (i: Int)Some[Int]
scala> foo("Alice")
==========
Name: Alice
==========
scala> foo(name = "Alice")
==========
Name: Alice
==========
scala> foo(age = 10)
==========
Age: 10
==========
scala> foo(name = "Alice", age = 10)
==========
Name: Alice
Age: 10
==========
- Evbn 14y agoYeah, not sure why there is so much confusion in pythonland over an issue that has a trivial solution that was discovered ages ago, moments after the problem first appeared.