val s2 = java.text.MessageFormat.format( "At {1,time} on {1,date}, there was {2} on planet {0}.","Hoth", new java.util.Date(), "a disturbance in the Force") println(s2) //At 10:14:54 on 2020-4-8, there was a disturbance in the Force on planet Hoth.
val s3 = "my name is %s, age is %d.".format("james", 30) println(s3) // my name is james, age is 30.
/** * %1$s 说明: * ->%1 参数位置 第一个参数("james") * ->$s 参数类型 字符串类型 */ val s4 = "%s-%d:%1$s is %2$d.".format("james", 30) println(s4) // james-30:james is 30.
val s5 = "%2$d age's man %1$s: %2$d %3$s".format("james", 30,"hello") println(s5) // 30 age's man james: 30 hello
// 设置步长 scala> 1 to 10 by 2 res11: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9)
//定义Long类型的Range scala> 1L to 10L by 3 res12: scala.collection.immutable.NumericRange[Long] = NumericRange(1, 4, 7, 10)
//定义Double类型的Range scala> 1.1 to 4.5 by 1.2 res16: scala.collection.immutable.NumericRange[Double] = NumericRange(1.1, 2.3, 3.5)
//定义Char类型的Range scala> 'a' to 'z' by 4 res21: scala.collection.immutable.NumericRange[Char] = NumericRange(a, e, i, m, q, u, y)
scala> val r3 = 1 to (11,2) //步长为2 r3: scala.collection.immutable.Range.Inclusive = Range(1, 3, 5, 7, 9, 11)
scala> val r4 = 1 to 11 by 2//步长为2 r4: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9, 11)
scala> val r5 = 1 until (11,2) //步长为2 r5: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9)
scala> val r6 = 1 until 11 by 2//步长为2 r6: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9)
scala> val r7 = (1 to 10 by 4) //步长为4 r7: scala.collection.immutable.Range = Range(1, 5, 9)
scala> val r8 = (1:BigInt) to 3 r8: scala.collection.immutable.NumericRange.Inclusive[BigInt] = NumericRange(1, 2, 3)
10.1 take drop splitAt
1 2 3 4 5 6 7
1 to 10 by 2 take 3// Range(1, 3, 5) 1 to 10 by 2 drop 3// Range(7, 9) 1 to 10 by 2 splitAt 2// (Range(1, 3),Range(5, 7, 9)) // 前10个质数 defprime(n:Int) = (! ((2 to math.sqrt(n).toInt) exists (i=> n%i==0))) 2 to 100 filter prime take 10
10.2 takeWhile, dropWhile, span
while语句的缩写
语句
说明
takeWhile (…)
等价于:while (…) { take }
dropWhile (…)
等价于:while (…) { drop }
span (…)
等价于:while (…) { take; drop }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
1 to 10 takeWhile (_<5) // (1,2,3,4) 1 to 10 takeWhile (_>5) // () //Takes longestprefixof elements that satisfy a predicate. 10 to (1,-1) takeWhile(_>6) // (10,9,8,7) 1 to 10 takeWhile (n=>n*n<25) // (1, 2, 3, 4) //如果不想直接用集合元素做条件,可以定义var变量来判断: //例如,从1 to 10取前几个数字,要求累加不超过30: var sum=0; val rt = (1 to 10).takeWhile(e=> {sum=sum+e;sum<30}) // Range(1, 2, 3, 4, 5, 6, 7) //注意:takeWhile中的函数要返回Boolean,sum<30要放在最后; 1 to 10 dropWhile (_<5) // (5,6,7,8,9,10) 1 to 10 dropWhile (n=>n*n<25) // (5,6,7,8,9,10) 1 to 10 span (_<5) // ((1,2,3,4),(5,6,7,8) List(1,0,1,0) span (_>0) // ((1), (0,1,0)) //注意,partition是和span完全不同的操作 List(1,0,1,0) partition (_>0) // ((1,1),(0,0))