alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (bug0325.scala)

This example Scala source code file (bug0325.scala) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Scala tags/keywords

array, array, char, e, list, q, richstring, richstring, rs, rs, string, string, test

The Scala bug0325.scala source code

case class RS(self: String) {

  // NB. "\\Q" + '\\' + "\\E" works on Java 1.5 and newer, but not on Java 1.4
  private def escape(ch: Char): String = ch match {
    case '\\' => "\\\\"
    case _ => "\\Q"+ch+"\\E"
  }

  def split(separator: Char): Array[String] = self.split(escape(separator))
	
  def split(separators: Array[Char]): Array[String] = {
    val re = separators.foldLeft("[")(_+escape(_)) + "]"
    self.split(re)
  }
}

object Test {
  def expect = List("a","b")
  def test(f: => Array[String], which: String) {
    try {
      val ret = f.toList
      if (ret != expect)
        println(which + " returned " + ret + " when expecting " + expect)
      else
        println(ret)
    } catch {
      case e@_ => println(which + " failed with " + e.getClass)
    }
  }
     
  def main(args: Array[String]) {
    val badChars = "?*{+([\\^.$"

    for (c <- badChars)
      test(("a"+c+"b").split(c),"RichString split('"+ c + "')")
    println

    for (c <- badChars)
      test(RS("a"+c+"b").split(c),"RS split('"+ c + "')")
    println

    val badCases = List(
      ']' -> "x]", '&' -> "&&",'\\' -> "\\x", '[' -> "[x",
      '^' -> "^x", '-' -> "x-z"
    )
    for ((c,str) <- badCases)
      test(("a"+c+"b").split(str.toArray),"RichString split(\""+ str + "\")")
    println
   
    for ((c,str) <- badCases)
      test(RS("a"+c+"b").split(str.toArray),"RS split(\""+ str + "\")")   
  }
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala bug0325.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.