如何检查字符串是否是 Scala 中的十进制数 [英] How to check to see if a string is a decimal number in Scala

查看:36
本文介绍了如何检查字符串是否是 Scala 中的十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Scala 还是很陌生,我几乎每天都在发现新的有趣的做事方式,但它们并不总是明智的,有时已经作为一种结构存在于语言中,我只是不知道他们.因此,通过该序言,我正在检查给定的字符串是否完全由数字组成,所以我正在做:

I'm still fairly new to Scala, and I'm discovering new and interesting ways for doing things on an almost daily basis, but they're not always sensible, and sometimes already exist within the language as a construct and I just don't know about them. So, with that preamble, I'm checking to see if a given string is comprised entirely of digits, so I'm doing:

def isAllDigits(x: String) = x.map(Character.isDigit(_)).reduce(_&&_)

这是明智的还是不必要的愚蠢?它有更好的方法吗?只是调用 x.toInt 并捕获异常更好,还是不那么惯用?两者是否有性能优势/缺点?

is this sensible or just needlessly silly? It there a better way? Is it better just to call x.toInt and catch the exception, or is that less idiomatic? Is there a performance benefit/drawback to either?

推荐答案

试试这个:

def isAllDigits(x: String) = x forall Character.isDigit

forall 采用一个函数(在本例中为 Character.isDigit),该函数采用集合元素类型的参数并返回一个 布尔值;如果函数对集合中的所有元素返回 true,则返回 true,否则返回 false.

forall takes a function (in this case Character.isDigit) that takes an argument that is of the type of the elements of the collection and returns a Boolean; it returns true if the function returns true for all elements in the collection, and false otherwise.

这篇关于如何检查字符串是否是 Scala 中的十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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