Reidar Sollid's Blog

Just another site

String split method to return a tuple

leave a comment »

So basically I thought this would be a cool thing to do in Scala, returning a tuple from the String split method.

val (str1,str2) = text.split(":")

But it doesn’t, String split returns an array.

val array:Array[String] = text.split(":")

So what can we do, so I was thinking “I can solve this with implicit conversion can’t I?”. Of course I can, so here is what I did. First I created a class with a function splitToTuple returning a tuple from the split. I wanted to split on io::println in Rust so that I could get content assist for the editor, if io:: is pressed I wanted the tuple to be returned as (“io”,””) to return all the functions in the io package.

class StringSplitToTuple(s: String) {
  def splitToTuple(regex: String): (String, String) = {
    s.split(regex) match {
      case Array(str1, str2) = (str1, str2)
      case Array(str1) = (str1, "")
      case _ = error("too many colons")

Then I needed an object to hold the implicit conversion.

object SplitToTuple {
  implicit def splitToTuple(regex: String) = new StringSplitToTuple(regex)

And viola, now I can get a tuple from Strings split method.

import SplitToTuple._
object Main extends App {
  val (str1, str2) =  "io::println".splitToTuple("::")

Written by reidarsollid

April 23, 2013 at 9:31 pm

Posted in Scala, software

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: