class base[T] () {
def tell(t: T) { }
}
class test[T](a: T, b: base[T]){
b.tell("sssssssssss")
}
val b = new base[String]()
val s:String = "12354555"
val t = new test[String](s, b)
I have two classes, one is class base , the other is test .
Class test has two params.
After run the code, I get such a type mismatch error.
error: type mismatch;
found : String("sssssssssss")
required: T
b.tell("sssssssssss")
^
one error found
In my code, already defined a type String b, but in class test the type of b is T .
At compilation moment type variable T in class test is not String , but you try to call it with String
Two possible solutions:
a) Set Lower bounds for paramter T
class test[T >: String](a: T, b: base[T]){
b.tell("sssssssssss")
}
b) Or change type of prameter b :
class test[T](a: T, b: base[String]){
b.tell("sssssssssss")
}
In the example you gave, T is a String, but it doesn't have to be. It could be anything.
You pass a String to b.tell() no matter what, but b.tell()'s argument type is not guaranteed to be a String.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.