Scala-可选参数,无需用户输入Some(...) [英] Scala - Optional Arguments without requiring user to input Some(...)

查看:177
本文介绍了Scala-可选参数,无需用户输入Some(...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计程序。我是Scala的新手,但似乎可以使用以下命令处理可选参数:

I am designing a program. I am new to Scala but it seems optional arguments are handled using the following:

def f1(my_string: Option[String] = None) = {

// Maybe do some pattern matching here to extract the value

}

但是,对于最终用户而言,这非常丑陋,因为他们将需要调用此函数,例如:

However, for an end user this is pretty ugly as they will need to call this function like:

f1(Some("foo")

是否有一种技术或模式可以将其变成:

Is there a technique or pattern to turn this into:

f1("foo"))

仍然可以使用可选参数吗?即f1()也可以使用吗?

and still work with an optional argument?i.e f1() also works?

我问的原因是我显然已经在不需要显式Some(..)的Scala库中使用了Scala库,但是在它们的源代码中,它们已经定义了上述函数。我个人将使用默认参数,但会徘徊于为什么这是一种设计模式。

The reason I ask is I have obviously used Scala libraries where adding an explicit Some(..) has not been necessary, but in their source code they have defined functions as above. I would personally use a default argument but wandering why this is a design pattern.

推荐答案

而不是 Option 您可以重载该方法。

Instead of Option you could overload the method.

f1() :ReturnType = {...}

f1(arg:String) :ReturnType = {...}

这篇关于Scala-可选参数,无需用户输入Some(...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆