For example I have a code like this:
class Foo(name: String = "", callback: String => String) {
def doCallback(arg: String): String = {
callback(arg)
}
}
Questions:
1. In Foo
class constructor, how to give callback
parameter a default value? Is it okay to set it to null
? Or is there better alternative?
class Foo(name: String = "", callback: String => String = null) {
...
}
2. If answer of question no. 1 is not a null
, how to do a check of callback
before calling it inside the doCallback
method? For example, suppose null
is acceptable, I might do it like this:
class Foo(name: String = "", callback: String => String = null) {
def doCallback(arg: String): String = {
if (callback != null) callback(arg) else "" // the checking of not null
}
}
class Foo(name: String = "", callback: Option[String => String] = None) {
def doCallback(arg: String): String = {
val call: Option[String] = callback.map(c => c(arg)) // which will either be None or Some(String)
call match {
case Some(s: String) => s
case None => null
}
}
}
Of course if you change the signature of doCallback
to Option[String]
you won't have to do pattern matching.
In general avoiding having null
s in Scala is a good practice. One benefit of which is not getting NullPointerException
s.
This approach however does force you to pass your callback
on class instantiation within Some()
.
Or, more in line with your original request:
class Foo(name: String = "", callback: String => Option[String] = {(s) => None}) {
def doCallback(arg: String): String = {
val call: Option[String] = callback(arg)
call match {
case Some(s: String) => s
case None => null
}
}
}
As others have said, it's good to wrap everything with Option
.
But if you just want the default result to be ""
, things can be a bit easier:
val alwaysEmpty = { given: String => "" }
class Foo(val doCallback: String => String = alwaysEmpty)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.