Scala in depth 6 Scala的类型系统 下
2014-12-28 09:36
330 查看
接上一篇。
1. Java中是否也有声明Upper bound 和 Lower boud的语法呢? 有的,比如:
List<E extends Numeric> List<E upper Integer>
2.Java中的 List<?> 和 List<Object> 有什么区别?
List<?> 代表 任意类型的 List都可以赋值给它
List<Object> 代表 List中元素的类型是任意的
3.Java的类型通常可以直接翻译成scala的类型。但是像 Iterator<?>, Iterator<? extends Component> 这样的类型怎么翻译呢?
Iterator[T] forSome { type T } 或 Iterator[_]
Iterator[T] forSome { type T <: Component }
关于forSome,Stack Overflow有个贴子介绍的很好:
http://stackoverflow.com/questions/15186520/scala-any-vs-underscore-in-generics
4.View bound
5. Context bound
x is of type A and there must be an implicit value B[A] available when calling method
foo. Context bounds can be rewritten as follows
示例:
1. Java中是否也有声明Upper bound 和 Lower boud的语法呢? 有的,比如:
List<E extends Numeric> List<E upper Integer>
2.Java中的 List<?> 和 List<Object> 有什么区别?
List<?> 代表 任意类型的 List都可以赋值给它
List<Object> 代表 List中元素的类型是任意的
package tstge; import java.util.*; public class Tst { public static void main(String[] args) { ArrayList<?> mylist1 = null; ArrayList<Object> mylist2 = null; ArrayList<Integer> mylist3 = new ArrayList<Integer>(); mylist2 = mylist3; // Error! type mismatch: cannot convert from ArrayList<Integer> to ArrayList<Object> mylist1 = mylist3; } }
3.Java的类型通常可以直接翻译成scala的类型。但是像 Iterator<?>, Iterator<? extends Component> 这样的类型怎么翻译呢?
Iterator[T] forSome { type T } 或 Iterator[_]
Iterator[T] forSome { type T <: Component }
关于forSome,Stack Overflow有个贴子介绍的很好:
http://stackoverflow.com/questions/15186520/scala-any-vs-underscore-in-generics
4.View bound
def foo[A <% B](x: A) = x意思是在调用foo方法的地方,必须能看到从A类型到B类型的转换函数,相当于
def foo[A](x: A)(implicit $ev0: A => B) = x
5. Context bound
def foo[A : B](x: A) = xThe foo method defines a constraint A : B. This constraint means that the parameter
x is of type A and there must be an implicit value B[A] available when calling method
foo. Context bounds can be rewritten as follows
def foo[A](x: A)(implicit $ev0: B[A]) = x当前上下文必须存在类型为B[A]的隐含值
示例:
def tabulate[T: ClassManifest](len: Int, f: Int => T) = { val xs = new Array[T](len) for (i <- 0 until len) xs(i) = f(i) xs }会被展开成
def tabulate[T](len: Int, f: Int => T)(implicit m: ClassManifest[T]) = { val xs = new Array[T](len) for (i <- 0 until len) xs(i) = f(i) xs }
相关文章推荐
- Scala in depth 6 Scala的类型系统 上
- Scala in depth 6 Scala的类型系统 中
- 【Scala类型系统】隐式转换与隐式参数
- day4-Scala模式匹配、类型系统
- 【Scala类型系统】自身类型(self type)引用
- C# in depth ( 第三章 用泛型实现参数化类型)
- C# in depth ( 第四章 可空类型)
- C# in Depth Third Edition 学习笔记-- 可空类型
- Scala模式匹配、类型系统与Spark源码阅读
- 【Scala类型系统】函数式Queue的简易实现
- c# in depth之泛型的类型约束详细
- scala 的模式匹配与类型系统
- 文件系统(in-depth)
- scala类型系统:13) context bounds
- scala类型系统:12) view bounds
- scala类型系统:19) Manifest与TypeTag
- C# in Depth Third Edition 学习笔记-- 值类型和引用
- c# in depth 之泛型实参的类型推断
- Scala讲座:类型系统和相关功能
- 第4集:Scala模式匹配、类型系统彻底精通与Spark源码阅读