定义数组:
val
active
= Array.
fill
(numRuns)(
true
)
val
costs = Array.
fill
(numRuns)(
0.0
)
var
activeRuns =
new
ArrayBuffer[Int] ++ (
0
until numRuns)
自定义类型:
type
WeightedPoint
= (Vector, Long)
def
testType(): Unit ={
type
WeightedPoint
= (
Vector
[Double], Long)
//自定义类型
val
v =
Vector
.fill(
10
)(
0.0
)
val
wp=
new
WeightedPoint(v,
1
)
println
(wp._1)
println(wp._2)
}
自定义条件检查函数:
def
require(requirement: Boolean) {
if
(!requirement)
throw new
IllegalArgumentException(
"requirement failed"
)
}
调用:
require
(x.size == y.size) //x:
Vector
, y:
Vector
Some(value)类型调用.get 得到值。
scala推荐在可能返回空的方法使用Option[X]作为返回类型。如果有值就返回Some[x](Some也是Option的子类),否则返回None,例如
def get(key: A): Option[B] = {if (contains(key))Some(getValue(key))elseNone}
获得Option后,可以使用get获得包含的值,或者使用getOrElse获得默认值如果isEmpty为true。
自定义List排序
object
testListTop {
implicit def
iterExt[
B
](iter:
Iterable
[
B
]) =
new
{ //new一个匿名类,会接收传进来的参数类型,返回一个新的类对象,接收的参数类型为Iterable,返回的匿名类中包含了top方法。(
隐式类
)
def
top[
C
](n: Int, f:
B
=>
C
)(
implicit
ord:
Ordering
[
C
]):
List
[
B
] = {
def
updateSofar (sofar:
List
[
B
], el:
B
):
List
[
B
] = {
//println (el + " - " + sofar)
if
(ord.compare(f(el), f(sofar.head)) >
0
)
(el :: sofar.tail).sortBy (f)
else
sofar
}
val
(sofar, rest) = iter.splitAt(n)
(sofar.toList.sortBy (f) /: rest) (updateSofar (_, _)).reverse
}
}
def
main(args: Array[
String
]) {
val
li =
List
(
4
,
3
,
6
,
7
,
1
,
2
,
9
,
5
).map(i => (i,
10
-i))
println
(li.top(
3
, _._2))
}
}