为什么将 Int => Int 传递给采用 AnyVal => Int 的函数会在 Int 扩展 AnyVal 时导致类型不匹配?

Why passing Int => Int to a function taking AnyVal => Int results in type mismatch when Int extends AnyVal?

我是 Scala 的新手,我很难将一个函数作为参数传递给另一个函数。我试图传递的函数应该有一个参数,但我不知道它的类型(但它确实是一个值):

object Sing
    def myFunc(myinnerfunc:(AnyVal)=>Int):Anyval
    {
    ...
    }

object main {
  def main(args : Array[String]): Unit ={
    val a = Sing.myFunc((x:Int)=>2*x:Int)
  }
}

我得到的错误是:

type mismatch : 
found : (Int)=>Int
required : (AnyVal)=>Int

您不知道它的类型,所以应该使用通用类型。不保证 AnyVal 是 Int,因此您不能只传递一个带有 Int 的函数:

def myFunc[T <: AnyVal](myinnerfunc: T => Int): Any = 0

myFunc((_: Int) * 2)

尽管 Int 扩展了 AnyVal,函数 myFunc 不能接受 Int => Int 因为在 Scala 中函数是

contravariant over its argument type, and covariant over its return type

这意味着 Int => Int 而不是 AnyVal => Int

的子类型
implicitly[(Int => Int) <:< (AnyVal => Int)]   // Error: Cannot prove

如果你知道函数参数是数字类型,那么考虑Numeric类型类解决方案

def myFunc[T](myinnerfunc: T => Int)(implicit num: Numeric[T]): T = ???