Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Can a literal reference itself?

Tags:

scala

I want to do something like this:

scala> "Hello world"(this.length -1)
res30: Char = d

This obviously doesn't work as I can't reference "Hello world" without first storing it as a val.

Is there some way to achieve this ?

like image 244
Rahul Avatar asked Jul 07 '11 05:07

Rahul


2 Answers

If you just want the last character of the string, you can just do:

scala> "Hello World".last
res0: Char = d

For a general problem, you might want to use the forward pipe operator, as shown below:

scala> "Hello World" |> { t => t(t.length - 1)  }
res1: Char = d

You can either define forward pipe operator as shown below, or use the one available in Scalaz.

scala> implicit def anyWithPipe[A](a: A) = new {
     |   def |>[B](f: A => B): B = f(a)
     | }
anyWithPipe: [A](a: A)java.lang.Object{def |>[B](f: (A) => B): B}
like image 84
missingfaktor Avatar answered Nov 15 '22 06:11

missingfaktor


You can't reference the literal itself, but you can create a block with a temporary variable local to that block.

scala> val lastChar = { val tmp = "Hello World"; tmp(tmp.length - 1) }
lastChar: Char = d

scala> tmp
<console>:8: error: not found: value tmp
like image 29
kassens Avatar answered Nov 15 '22 06:11

kassens