Scala:可以直接引用本身吗? [英] Scala: Can a literal reference itself?

查看:46
本文介绍了Scala:可以直接引用本身吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

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

这显然是行不通的,因为我不能在不先将Hello world"存储为 val 的情况下引用它.

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 ?

推荐答案

如果你只想要字符串的最后一个字符,你可以这样做:

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

您可以定义如下所示的前向管道运算符,也可以使用 Scalaz 中可用的运算符.

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}

这篇关于Scala:可以直接引用本身吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆