在某些方法中,我想强制命名参数。原因是未指定参数顺序的自动生成代码(并将保持这种方式)。
我能得到的最接近的是
private val _forceNamed: Object = new Object()
def doSomething(forceNamed: Object = _forceNamed, arg1: String, arg2: String, ...): Unit = {
if (forceNamed != _forceNamed) {
throw Exception(something)
}
// actually do stuff
}
Run Code Online (Sandbox Code Playgroud)
但是,这只会在运行时失败,而在编译时失败会更好。
如果你想堵住能够传入的漏洞null,可以使用值类作为守卫。
scala> :paste
// Entering paste mode (ctrl-D to finish)
class Foo {
import Foo._
def foo(x: Bar = bar, a: String, b: String) = println(a + b)
}
object Foo {
private[Foo] class Bar(val i: Int) extends AnyVal
private val bar = new Bar(42)
}
// Exiting paste mode, now interpreting.
defined class Foo
defined object Foo
scala> val f = new Foo
f: Foo = Foo@4a4f9c58
scala> f.foo(null, "", "")
<console>:13: error: type mismatch;
found : Null(null)
required: Foo.Bar
f.foo(null, "", "")
^
Run Code Online (Sandbox Code Playgroud)