关于Kotlin中泛型的类型参数
我正在学习kotlin语言,我无法区分这些示例,尤其是泛型的“where”子句中的可空类型。 你能告诉我区别吗 案例1关于Kotlin中泛型的类型参数,kotlin,Kotlin,我正在学习kotlin语言,我无法区分这些示例,尤其是泛型的“where”子句中的可空类型。 你能告诉我区别吗 案例1 class Foo<T> where T: Comparable<T> class Foo<T> where T: Comparable<T?> class Foo<T> where T: Comparable<T>? class Foo<T> where T: Comparable<T?
class Foo<T> where T: Comparable<T>
class Foo<T> where T: Comparable<T?>
class Foo<T> where T: Comparable<T>?
class Foo<T> where T: Comparable<T?>?
Foo类,其中T:可比
Foo类,其中T:可比
F类,其中T:可比?
F类,其中T:可比?
案例2
class Foo<T> where T: Comparable<T>? {
// If a class is declared like above, is a type 'T' already nullable?
// Then,
fun bar(value: T?) { // Should I declare a member function like this to accept null or
// do something
}
fun bar(value: T) { // Should I declare like this instead?
}
}
Foo类,其中T:可比?{
//如果像上面那样声明了一个类,那么类型“T”是否已经可以为null?
//那么,
funbar(value:T?{//我应该声明这样的成员函数接受null还是
//做点什么
}
乐趣条(value:T){//我应该这样声明吗?
}
}
首先,要区分T:Comparable
和T:Comparable
,请看以下示例。区别在于是否可以将T
与T?
进行比较
class Bar1(var bar : Int) : Comparable<Bar1>{
override fun compareTo(other : Bar1) : Int {
return bar - other.bar
}
}
class Bar2(var bar : Int) : Comparable<Bar2?>{
override fun compareTo(other : Bar2?) : Int {
return bar - ( other?.bar ?: 0 )
}
}
fun main(){
println(Bar1(1) > Bar1(2))
val bar2 : Bar2? = Bar2(2)
println(Bar2(1) > bar2)
}
不会编译<代码>条形码1必须展开
其次,为了区分类Foo,其中T:compariable?
和类Foo,其中T:compariable?
,它与compariable无关。请看下面的简化示例
class Foo1<T>(val t : T) where T : Int{
override fun toString() : String{
return "$t"
}
}
class Foo2<T>(val t : T) where T : Int?{
override fun toString() : String{
return "$t"
}
}
fun main(){
println(Foo1(5))
val i : Int? = 5
println(Foo2(i))
}
class Foo1(val t:t),其中t:Int{
重写funtostring():String{
返回“$t”
}
}
类Foo2(val t:t)其中t:Int{
重写funtostring():String{
返回“$t”
}
}
主要内容(){
println(Foo1(5))
val i:Int?=5
println(Foo2(i))
}
输出:
五,
五,
不同之处在于println(Foo1(i))
不会编译<代码>i必须展开
class Foo1<T>(val t : T) where T : Int{
override fun toString() : String{
return "$t"
}
}
class Foo2<T>(val t : T) where T : Int?{
override fun toString() : String{
return "$t"
}
}
fun main(){
println(Foo1(5))
val i : Int? = 5
println(Foo2(i))
}