- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Comparing 2 strings
Thu, 2009-03-05, 09:11
Hi,
I'm trying to make a method to compare 2 strings.
def compareString(one:String, two:String): String {
if (one.compareTo(two) > 0) one
else two
}
But this doesn't work.
also I am trying to put those 2 in a List and then sort and to take the last. But I'm not doing well because I only could declare the list
scala> var x=List[String] ("one", "two")
x: List[String] = List(one, two)
but how can I sort a list?
Thanks.
I'm trying to make a method to compare 2 strings.
def compareString(one:String, two:String): String {
if (one.compareTo(two) > 0) one
else two
}
But this doesn't work.
also I am trying to put those 2 in a List and then sort and to take the last. But I'm not doing well because I only could declare the list
scala> var x=List[String] ("one", "two")
x: List[String] = List(one, two)
but how can I sort a list?
Thanks.
Sat, 2009-03-07, 01:17
#2
Re: Comparing 2 strings
I was thinking that "one max two" would be more Scalaish API for the
function in question. Which lead be to check the Ordered trait.
Why isn't max and min defined on Orderd rather than all the Rich* wrappers?
BR,
John
On Thu, Mar 5, 2009 at 9:11 AM, Poperecinii Timur
wrote:
> Hi,
>
> I'm trying to make a method to compare 2 strings.
>
> def compareString(one:String, two:String): String {
> if (one.compareTo(two) > 0) one
> else two
> }
>
> But this doesn't work.
>
> also I am trying to put those 2 in a List and then sort and to take the
> last. But I'm not doing well because I only could declare the list
>
>
> scala> var x=List[String] ("one", "two")
> x: List[String] = List(one, two)
>
> but how can I sort a list?
>
> Thanks.
>
>
> Hi,
>
> I'm trying to make a method to compare 2 strings.
>
> def compareString(one:String, two:String): String {
> if (one.compareTo(two) > 0) one
> else two
> }
>
> But this doesn't work.
Would always be good to be more precise about "doesn't work".
That saves others the work to copy and run your example to replay
the symptoms or to guess about them out of blue sky.
Back to topic: I now guess you get this error, which I got when
copying and running your example:
scala> def compareString(one: String, two:String): String {
| if (one.compareTo(two) > 0 ) one
:2: error: illegal start of declaration
if (one.compareTo(two) > 0 ) one
^
Result: You declared your function without the equal sign.
between result type and opening brace. Use instead:
scala> def compareString(one: String, two:String): String = {
^^^^^^
Regarding sort:
scala> val lst = List[String] ("two", "ze end", "one", "begin")
lst: List[String] = List(two, ze end, one, begin)
scala> lst.sort((a:String, b:String) => a < b)
res7: List[String] = List(begin, one, two, ze end)
KR
Det