简体   繁体   English

如何漂亮地打印scala中Option返回的值?

[英]How to pretty print value returned by Option in scala?

I have a function which returns an "Option[myDataStructure]. When I call this from Zeppelin notebook, it says that it cannot call "show()" on the value as it of type "option". Is there any other way using which I can pretty print my returned value as a dataset? Printing using println is really clumsy. 我有一个返回“ Option [myDataStructure]”的函数。当我从Zeppelin笔记本中调用此函数时,它说它不能在值上调用“ show()”,因为它的类型为“ option”。是否还有其他方法可以使用我可以将返回的值作为数据集打印出来吗?使用println打印真的很笨拙。

val returnValue: Option[myDataStructure] = myFunction(a,b)
returnValue.show(10,false)

You can use foreach to perform side-effecting action on Option : 您可以使用foreachOption上执行副作用操作:

returnValue.foreach(_.show(10,false))

It will only run if the Option is Some and therefore it's safer than calling get which may throw java.util.NoSuchElementException in the case when Option is None . 它只会在OptionSome的情况下运行,因此,与在调用OptionNone的情况下调用get可能引发java.util.NoSuchElementException的安全性更高。

您可以通过使用get获得Option中的值

returnValue.get.show(10,false)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM