Oktatás * Programozás 2 * Szkriptnyelvek * levelezősök Félévek Linkek * kalendárium |
Scala /
implicit class
In Python you take every n-th character of a string like this: >>> s = 'hello python and scala' >>> s[::2] 'hlopto n cl' In Scala you can't do it that easily (or at least I haven't found it yet). I asked this question on IRC at #scala and we came up with this solution: scala> val s = "hello python and scala" scala> (for (i <- 0 until s.length if i % 2 == 0) yield s(i)).mkString res16: String = hlopto n cl Make it an implicit classUsing implicit classes, Scala allows you to add new operations to existing classes, no matter whether they come from Scala or Java! Jacoby6000 suggested to make it an auxiliary method for strings. In Scala you can do it with an implicit class. Here is a complete solution: #!/usr/bin/env scala import scala.math object Implicits { implicit class PimpedString(str: String) // we want to extend the String class with our method { def everyNthChar(skipNum: Int): String = { (for (i <- str.indices if i % skipNum == 0) yield str(i)).mkString } // other methods I want strings to have go here } implicit class PimpedInt(x: Int) { def pow(y: Int): Int = { math.pow(x, y).toInt } // other methods I want ints to have go here } } object Main extends App { import Implicits._ // Lookie here! Our method looks like a normal string method: println("Hey Look, I can use methods from PimpedString!".everyNthChar(3)) } Main.main(args) "I usually have an object that contains all of my implicits called " Yet another example object Implicits { implicit class PimpedString(s: String) { def center(n: Int): String = { "%s%s".format(" " * ((n - s.length) / 2), s) } } } object Main { import Implicits._ def main(args: Array[String]) { // center the given string using a fixed width (actually, the whitespaces are removed on the right side) println("*".center(9)) // " * " println("***".center(9)) // " *** " } } |
Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |