Scala syntax problem
The following code can be compiled
开发者_如何学运维 def isEven(a:Int)=
if (a%2==0) true else false
def main(args: Array[String]) {
List(1, 10) filter isEven foreach println
but if I change to following ( List(1,10) --> List(1 to 10))
def isEven(a:Int)=
if (a%2==0) true else false
def main(args: Array[String]) {
List(1 to 10) filter isEven foreach println
}
What's difference between List(1,10) and List(1 to 10) ?
List(1, 2)
is simply a list with two Int
elements: 1 and 2. The expression 1 to 10
creates a Range
instance, so List(1 to 10)
is a list with one element: a Range
.
List(1, 10)
is a List[Int]
whereas List(1 to 10)
is a List[Range]
. Observe the types in the following REPL session:
scala> 1 to 10
res3: scala.collection.immutable.Range.Inclusive with scala.collection.immutable.Range.ByOne = Range(1, 2, 3, 4, 5, 6, 7
, 8, 9, 10)
scala> List(1 to 10)
res4: List[scala.collection.immutable.Range.Inclusive with scala.collection.immutable.Range.ByOne] = List(Range(1, 2, 3,
4, 5, 6, 7, 8, 9, 10))
scala> List(1, 10)
res5: List[Int] = List(1, 10)
missingfaktor is right, so this is just an addition.
If you want a List[Int]
with numbers from 1 to 10, you can write
List(1 to 10:_*)
or
1 to 10 toList
精彩评论