我突然遇到了这个(意想不到的)情况:
def method[T](x: T): T = x
scala> method(1)
res4: Int = 1
scala> method(1, 2)
res5: (Int, Int) = (1,2)
Run Code Online (Sandbox Code Playgroud)
为什么在两个或更多参数方法的情况下返回并推断出一个元组但是抛出关于参数列表的错误?是故意吗?也许这种现象有一个名字?
在Scala(2.7.7final)中,该Predef.println
方法被定义为具有以下签名:
def println (x : Any) : Unit
Run Code Online (Sandbox Code Playgroud)
怎么来,那么以下工作:
scala> println(1,2)
(1,2)
Run Code Online (Sandbox Code Playgroud)
编译器是否自动将以逗号分隔的参数列表转换为元组?通过什么魔术?这里是否存在隐式转换,如果是,那么哪一个?
为什么这样做:
val x = Map[Int,Int]()
val y = (1, 0)
x + y
Run Code Online (Sandbox Code Playgroud)
但不是吗?
val x = Map[Int,Int]()
x + (1, 0)
Run Code Online (Sandbox Code Playgroud)
产生的错误是:
<console>:11: error: type mismatch;
found : Int(1)
required: (Int, ?)
x + (1,0)
^
Run Code Online (Sandbox Code Playgroud)
如果我要进入(1,0)
REPL,它会正确输入(Int,Int)
.
我应该补充说这很好用:
x + (1 -> 0)
Run Code Online (Sandbox Code Playgroud) 这是我项目中类型安全的麻烦违规,所以我正在寻找一种方法来禁用它.似乎如果函数采用AnyRef(或java.lang.Object),您可以使用任何参数组合调用该函数,Scala会将参数合并到Tuple对象中并调用该函数.
在我的情况下,该函数不期望一个元组,并在运行时失败.我希望在编译时捕获这种情况.
object WhyTuple {
def main(args: Array[String]): Unit = {
fooIt("foo", "bar")
}
def fooIt(o: AnyRef) {
println(o.toString)
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
(foo,bar)
Run Code Online (Sandbox Code Playgroud) 假设我有两个函数f
和g
:
val f: (Int, Int) => Int = _ + _
val g: Int => String = _ + ""
Run Code Online (Sandbox Code Playgroud)
现在我想用它们来组合它andThen
来获得一个功能h
val h: (Int, Int) => String = f andThen g
Run Code Online (Sandbox Code Playgroud)
不幸的是它没有编译:(
scala> val h = (f andThen g)
<console> error: value andThen is not a member of (Int, Int) => Int
val h = (f andThen g)
Run Code Online (Sandbox Code Playgroud)
为什么不把它编译,我该如何撰写f
并g
获得(Int, Int) => String
?
我正在尝试在Scala中使用JodaTime.所以我做了
import org.joda.time.DateTime
val dt = new DateTime(2011, 10, 8, 18, 30) // try to set to 6:30 pm, Oct 8, 2011
Run Code Online (Sandbox Code Playgroud)
不幸的是,Scala认为我正在尝试使用DateTime(Object)构造函数而不是5 int构造函数,并且毫不奇怪,Tuple5不是JodaTime所期望的那种对象.
如何告诉Scala使用5-int构造函数?
托德
我正在scala中迈出第一步,这里是一个"hello world"代码:
package test
object Main {
def main(args: Array[String]): Unit = {
println("Blabla something : " + 3)
println("Blabla something : " , 3)
}
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出:
Blabla something : 3
(Blabla something : ,3)
Run Code Online (Sandbox Code Playgroud)
为什么在第二行打印括号以及","?我期待与第一行相同的输出.
注意:我尝试搜索 scala println括号等等,但我得到的是关于如何从代码中删除括号的帖子,而不是从输出中删除.
如何将某个类型的元组的Option明确设置为None?
scala> var c = Some(1,1)
c: Some[(Int, Int)] = Some((1,1))
scala> c = None
<console>:11: error: type mismatch;
found : None.type
required: Some[(Int, Int)]
c = None
^
scala> None()
<console>:11: error: None.type does not take parameters
None()
^
scala> c = None()
<console>:11: error: None.type does not take parameters
c = None()
^
scala> c = None.Int
<console>:11: error: value Int is not a member of object None
c = None.Int
^
scala> c = None(Int, Int)
<console>:11: …
Run Code Online (Sandbox Code Playgroud)