我对Scala很新。我想将一个字符串指定为变量名:
val names = Vector("a","b","c")
for (name <~ names){
val <xyz> = "test"
}
我想将三个变量指定为:
a: String = test
b: String = test
c: String = test
如何编码以获得此结果?
答案 0 :(得分:1)
我首先误解了你的问题。
scala> map.get ("b")
res9: Option[String] = Some(test)
scala> map.get ("f")
res10: Option[String] = None
这称为Map,它的使用方式如下:
val (a, b, c) = ("test", "test", "test")
a: String = test
b: String = test
c: String = test
如果你只是搜索一个简短的表格来初始化3个变量,你可以这样做:
$(window).scroll(function(){
var wintop = $(window).scrollTop();
var docheight = $(document).height();
var winheight = $(window).height();
var scrolled = (wintop/(docheight-winheight))*100;
$('.scroll-line').css('width', (scrolled + '%'));
});
答案 1 :(得分:1)
添加到user unknown答案,您可以在Vector
上使用模式匹配,但如果您只想创建具有相同值的三个变量,则远非优雅。正如用户未知指出的那样,您可以通过元组进行模式匹配:val (a, b, c) = ("test", "test", "test")
val namesList = List("a", "b", "c")
val a :: b :: c :: Nil = for {
name <- namesList
} yield "test"
// a: String = test
// b: String = test
// c: String = test
val namesVector = Vector("a", "b", "c")
val d +: e +: f +: Vector() = for {
name <- namesVector
} yield "test"
// a: String = test
// b: String = test
// c: String = test
答案 2 :(得分:1)
嗯......有一种方法可以使用 Scala Macro 和Scala meta来实现这一目标。例如:
object VarrApp extends App {
// create a Varr annotation, this in the compile time, will automatically expand the names Vector and generate these variables
@Varr
val names = Vector("a", "b", "c")
println(a) // test
println(b) // test
println(c) // test
}
实现这一目标:
1.为宏创建一个子模块,项目结构如:
project:
macros-submodule/src/main/scala/Varr.scala
src/main/scala/VarrApp.scala
2.add Scala元依赖,与文档一样,添加天堂编译器插件,如:
addCompilerPlugin(
"org.scalameta" % "paradise" % "3.0.0-M7" cross CrossVersion.full),
并在 scalacOptions 中启用 macroparadise ,例如:
scalacOptions ++= Seq("-Xplugin-require:macroparadise")
3.实现Varr
注释,例如:
import scala.annotation.StaticAnnotation
import scala.meta._
class Varr extends StaticAnnotation {
inline def apply(defn: Any): Any = meta {
defn match {
case q"val $name = Vector(..$paramss)" => {
val stats = paramss.map {
case i: Lit =>
s"""val ${i.value} = "test"""".parse[Stat].get
}
q"""
..$stats
"""
}
case _ => abort("illegal stats")
}
}
}