Scala: Can a literal reference itself?

前端 未结 2 574
名媛妹妹
名媛妹妹 2020-12-20 23:08

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 refere

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-20 23:47

    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}
    

提交回复
热议问题