English 中文(简体)
报表范围变量
原标题:If-statement scoped variables
  • 时间:2012-01-13 03:06:39
  •  标签:
  • scala

我往往想在发言时产生范围很广的变量。 有些计算仅与某一具体数据有关,如果说的话——用临时变数 bad坏对外部范围进行污染。

What I would like to do:

val data = (whatever)

if (val x = data*2+5.4345/2.45; val y = data/128.4; x*y < 10) 
  x * y
else
  x * 2

println(x) //ERROR!

一种替代办法是:

val data = (whatever)

if (data*2+5.4345/2.45*data/128.4 < 10) 
  data*2+5.4345/2.45*data/128.4
else
  data*2+5.4345/2.45 * 2

The obvious alternative I m trying to avoid:

val data = (whatever)
val x = data*2+5.4345/2.45
val y = data/128.4

if (x*y < 10) 
  x*y
else
  x * 2

println(x) //OK

Is something like this possible in Scala? Is there a decent workaround? If not, what other languages support an idea like this?

最佳回答

由于if in Scala is an expression, i.e. itsam a Value, 通常由您对if/code>的表述确定某种价值。 因此,你的第三种选择只是罚款:把它放在法典的栏目中,即:

val data = (whatever)
val myValue = {
  val x = data*2+5.4345/2.45
  val y = data/128.4

  if (x*y < 10) 
    x*y
  else
    x * 2
}

None of the vals declared within the block are available outside it.

问题回答

You can use a pattern match:

val data = 123

val (result, x) = (data*2+5.4345/2.45, data/128.4) match {
  case (x, y) if x * y < 10 => (x * y, x)
  case (x, _)               => (x * 2, x)
}

println(x)

包括<代码>x* yx* 2,视其计算结果而定;<代码>x 载有按要求分列的<编码>*2+5.4345/2.45数值。

你们能够为它创造空间。

{
  val x = data*2+5.4345/2.45
  val y = data/128.4;
  if ( x*y < 10) 
    x * y
  else
    x * 2
}

或更清楚,

locally {
  val x = data*2+5.4345/2.45
  val y = data/128.4;
  if ( x*y < 10) 
    x * y
  else
    x * 2
}




相关问题
How to flatten a List of different types in Scala?

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]] I tried to zip them and I ...

To use or not to use Scala for new Java projects? [closed]

I m impressed with Twitter and investigating to use Scala for a new large scale web project with Hibernate and Wicket. What do you think about Scala, and should I use it instead of Java? EDIT: And, ...

Why does Scala create a ~/tmp directory when I run a script?

When I execute a Scala script from the command line, a directory named "tmp" is created in my home directory. It is always empty, so I simply deleted it without any apparent problem. Of course, when I ...

Include jar file in Scala interpreter

Is it possible to include a jar file run running the Scala interpreter? My code is working when I compile from scalac: scalac script.scala -classpath *.jar But I would like to be able to include a ...

Scala and tail recursion

There are various answers on Stack Overflow which explain the conditions under which tail recursion is possible in Scala. I understand the limitations and how and where I can take advantage of tail ...

热门标签