我正在尝试根据输入创建一个执行其他函数(返回字符串)的函数.
例如:
例如:
def execute(input: String) = { val actions = Map("foo" -> someObject.doStuff(),"bar" -> someObject.doThing()) actions.get(input) }
解决方法
object someObject { def doStuff() = "foo" def doThing() = "bar" } //if you need a string as a return value. //there will be empty string for missing keys def execute(input: String):String = { val actions = Map( "foo" -> someObject.doStuff _,"bar" -> someObject.doThing _ ) actions.getorElse(input,()=>"")() } //if you need an Option[String] as a return value. //there will be None value for missing keys def executeOption(input: String):Option[String] = { val actions = Map( "foo" -> someObject.doStuff _,"bar" -> someObject.doThing _ ) actions.get(input).map(_()) }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。