第256页 第17章 类型参数(习题)
- 章节名:第17章 类型参数(习题)
- 页码:第256页 2014-01-02 13:53:29
// 习题1 class ImmutablePair[T, S](fst: T, snd: S){ private val pair = (fst, snd) def swap() = new ImmutablePair(pair._2, pair._1) override def toString() = "(" + pair._1 +", " + pair._2 + ")" } object ImmutablePair { def apply[T, S](fst: T, snd: S) = new ImmutablePair(fst, snd) //习题3 def swap[T, S](p: ImmutablePair[T, S]) = ImmutablePair(p.pair._2, p.pair._1) } // 习题2 class MutablePair[T](fst: T, snd: T) { private var pair = (fst, snd) def swap() {pair = (pair._2, pair._1)} override def toString() = "(" + pair._1 + ", " + pair._2 + ")" } object MutablePair { def apply[T](fst: T, snd: T) = new MutablePair(fst, snd) } // 习题4 // 因为Student是Person的子类型,子类型可以自动转为超类型。 // 习题5 // RichInt是为了服务Int,同时存在Int到RichInt的隐式转换。 // 使用视图界定时Int隐式转换为RichInt,从而可以转换为Comparable[Int]。 // 习题6 def middle[T](a: Iterable[T]) = a.slice((a.size-1) / 2, a.size).head // 习题7 // 略 // 习题8 // 因为可变类型改变的是自身的第一个元素,该元素类型为T,替换进来的元素类型为R,R >: T; // 将超类型当作子类型是行不通的。 // 习题9 // 假定可以不用限制方法参数,那么对实际类型为NastyDoublePair的Pair[Any]调用replace("Hello")时, // 调用的是NastyDoublePair中重写了的replaceFirst,而其要求的是Double,所以会出错:type mismatch。 // 习题10 class Pair[S, T](private var first: S, private var second: T) { def swap(implicit ev1: T =:= S, ev2: S =:= T) = { val temp = first first = second second = temp } override def toString() = "(" + first + ", " + second + ")" }
14人阅读
atlarge对本书的所有笔记 · · · · · ·
-
第190页 第13章 集合(习题)
// 习题1 def indexes(str: String) = { str.zipWithIndex.groupBy(_._1).map { tuple => ...
-
第208页 第14章 模式匹配与样例类(习题)
// 习题2 def swap(v: (Int, Int)) = { v match { case (x, y) => (y, x) } } // 习题3 im...
-
第256页 第17章 类型参数(习题)
> 查看全部4篇
说明 · · · · · ·
表示其中内容是对原文的摘抄