I am not a Scala expert, but your code behaves exactly as I expected.
First, you need to know that a method type parameter is not necessarily associated with a class.
For example, the following Scala is valid.
class Test1 { def test[A] (x: A) = println(x) }
And the following is also valid Scala code, the only difference is that it does not use type A at all.
class Test2[A] { def test (x: Int) = println(x) }
So, I think itβs clear now, first you created an instance of MyTest [Int], and thatβs fine.
scala> val test = new MyTest[Int] test: MyTest[Int] = MyTest@308ff65f
Then you call checkString [A, Int] without specifying type A, since this is a general function, the compiler should infer which type is A.
scala> test.checkString("String",1) Value is a String x is not a String res7: java.lang.String = String
Note:
At this point in time, Scala already knows that x must be an Int and its type is fixed, since you provide it with MyTest [Int]. Thus, the following code will give a compilation error.
scala> val t = new MyTest[Int] t: MyTest[Int] = MyTest@cb800f scala> t.checkString ("A", "B") <console>:8: error: type mismatch; found : java.lang.String("B") required: t.MyType t.checkString ("A", "B")
Now the compiler is looking at the arguments that you provided, and found that it is
checkString ("String", 1)
which corresponds
checkString (value: A, x: Int)
So, now the compiler knows type A in checkString [A, Int] should be a string, and if you do all this manually, your code will look like this.
scala> val test = new MyTest[Int] test: MyTest[Int] = MyTest@5bda13 scala> test.checkString[String]("String", 1) Value is a String x is not a String res1: String = String scala> test.checkString[Int] (3, 4) Value is not a String x is not a String res4: Int = 3 scala> test.checkString[Int] ("String", 4) <console>:8: error: type mismatch; found : java.lang.String("String") required: Int test.checkString[Int] ("String", 4) ^