Cay Horstmann的书"Scala for the impatient"的一个非常简单的练习让我感到困惑.这是关于primary
,auxiliary
和default primary
构造函数:
ex 5.10: 考虑上课
class Employee(val name: String, var salary: Double) {
def this() { this("John Q. Public", 0.0) }
}
Run Code Online (Sandbox Code Playgroud)
重写它以使用显式字段和默认主构造函数.
我不确定我应该这样做.你们有些人可以提出解决方案吗?
但是,试图解决这个练习可能让我意识到我之前没有注意到关于主构造函数和val
字段的东西(你可以看到,我不太确定):
如果我说一个val
字段(如上面name
的Employee
类)只能通过primary
构造函数初始化而不是一个字段,我是对的auxiliary
吗?在后一种情况下,编译器将其视为对val
导致错误的字段的重新分配.
起初我认为val
字段是java中最终字段的粗略等价,期望在任何构造函数中第一次分配它们是合法的,但似乎我错了.
我对这可能只是一个疯狂的猜测并不十分满意,所以如果有人能给我更准确的信息,我会很感激.
我正在尝试从代理后面执行(在IntelliJ IDE或sbt命令行中)这个非常基本的调度片段:
import dispatch._
val svc = url("http://api.hostip.info/country.php")
val country = Http(svc > as.String)
println(country())
Run Code Online (Sandbox Code Playgroud)
而我所能得到的只是一个例外:
java.net.ConnectException: Connection timed out: no further information to
http://api.hostip.info/country.php java.util.concurrent.ExecutionException:
java.net.ConnectException: Connection timed out: no further information
to http://api.hostip.info/country.php
Run Code Online (Sandbox Code Playgroud)
我尝试没有确定的结果来设置通常的vm参数:
-Dhttp.proxyHost=
_my_proxy_host_ -Dhttp.proxyPort=80
并仍然得到相同的异常.
另一方面,以下代码段运行良好:
import dispatch._
val svc = url("http://api.hostip.info/country.php") setProxyServer(new com.ning.http.client.ProxyServer(myproxyhost,80))
val country = Http(svc > as.String)
println(country())
Run Code Online (Sandbox Code Playgroud)
因为它看起来不太美观,也不像scala-ish,我想知道在这种情况下它是否真的应该是我应该做的.
如果提前感谢,欢迎任何帮助.
首先,让我提前道歉,因为我在堆栈溢出时发布的第一个问题是什么,可能是一个非常愚蠢的问题.
由于scala中的Map使用以下语法进行实例化:
val myMap=Map(1->”value1”,2->”value2”)
Run Code Online (Sandbox Code Playgroud)
我期待Map对象scala.collection.immutable
提供一个apply
带有大致类似的签名的方法:
def apply[A,B](entries :(A,B)*):Map[A,B]
Run Code Online (Sandbox Code Playgroud)
显然我应该是盲人,但我找不到这样的方法.它在哪里定义?
此外,也有人给我约的用途信息Map1
,Map2
,Map3
,Map4
在定义的类Map
的对象?它们应该由开发人员使用还是仅由语言和/或编译器在内部使用?它们是否与我上面提到的地图实例化方案有某种关系?
在此先感谢您的帮助.
我担心这是另一个菜鸟问题.
我想要做的是使用a Map
来计算一个单词出现在poe ...中的频率,然后将结果打印到控制台.我转到下面的代码,我相信它正在工作(虽然可能不是很惯用):
val poe_m="""Once upon a midnight dreary, while I pondered weak and weary,
|Over many a quaint and curious volume of forgotten lore,
|While I nodded, nearly napping, suddenly there came a tapping,
|As of some one gently rapping, rapping at my chamber door.
|`'Tis some visitor,' I muttered, `tapping at my chamber door -
|Only this, and nothing more.'"""
val separators=Array(' ',',','.','-','\n','\'','`')
var words=new collection.immutable.HashMap[String,Int]
for(word<-poe_m.stripMargin.split(separators) if(!word.isEmpty))
words=words+(word.toLowerCase -> (words.getOrElse(word.toLowerCase,0)+1))
words.foreach(entry=>println("Word : "+entry._1+" …
Run Code Online (Sandbox Code Playgroud)