加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在函数应用程序中找不到隐式参数

发布时间:2020-12-16 10:01:35 所属栏目:安全 来源:网络整理
导读:如果我定义一个只接受数字的打印功能: def print[T % Number](value:T) {}print: [T](value: T)(implicit evidence$1: (T) = java.lang.Number)Unit 我可以打电话给上面的: print(5)print(5.5)print(6L) 但不是字符串: print("aaa") console:7: error: co
如果我定义一个只接受数字的打印功能:

def print[T <% Number](value:T) {}
print: [T](value: T)(implicit evidence$1: (T) => java.lang.Number)Unit

我可以打电话给上面的:

print(5)
print(5.5)
print(6L)

但不是字符串:

print("aaa")  
<console>:7: error: could not find implicit value for evidence parameter of type (java.lang.String) => java.lang.Number
       print("aaa")

这是预料之中的.

但是,如果我将打印功能定义为:

def print2[T <% Number]: T => Unit = value => { } 
print2: [T](implicit evidence$1: (T) => java.lang.Number)(T) => Unit

注意隐含参数是第一个参数而不是最后一个参数.

如果我尝试手动定义上述功能:

def print3[T](implicit f: (T) => java.lang.Number)(value:T):Unit =  { }  
<console>:1: error: '=' expected but '(' found.
       def print3[T](implicit f: (T) => java.lang.Number)(value:T):Unit =  { }

基本上上面不是一个有效的函数定义,但编译器在我之前定义print2时创建它.

当我用Int调用print2时:

print2(5)
<console>:7: error: type mismatch;
 found   : Int(5)
 required: (?) => java.lang.Number
       print2(5)

如果我参数化它:

print2[Int](5)
<console>:7: error: type mismatch;
 found   : Int(5)
 required: (Int) => java.lang.Number
       print2[Int](5)

它看起来无法从scala.Int =>中找到隐式转换.为java.lang.Integer.

如何重新定义打印,使其返回功能并以正确的方式访问含义?

解决方法

这里的问题是你传递5作为隐式参数.

现在我在电脑上,进行了一些修正:

def print[T <% Number](value:T) {}

你称之为函数,但它是一种方法.

def print2[T <% Number]: T => Unit = value => { }

再次,你称之为一个功能.实际上,它是一个返回函数的方法.该方法接收一个类型参数T和一个隐式参数.

print2(5)

因此,在这里,您将方法print2调用为5作为其隐式参数.类型T尚未被推测,因为它首先试图使5符合预期类型T =>数.但是,由于5不符合Function1 [T,Number],因此即使没有推断T也会失败.

有很多方法可以调用print2.例如:

print2(implicitly[Int => Number])
print2[Int]
(print2: Int => Unit)
val f: Int => Unit = print2

但是,要调用print2返回的函数,必须避免使(5)看起来像方法print2的隐式参数.实际上只有一个案例需要不同的东西:

print2(implicitly[Int => Number])(5)
print2[Int].apply(5)
(print2: Int => Unit)(5)
val f: Int => Unit = print2; f(5)

现在,大多数这些示例都有显式的,而不是推断的类型参数.让我们考虑一下它会缺席会发生什么:

print2.apply(5)

因为没有参数传递给print2,所以它选择符合T的边界的最具体类型.由于T没有边界,因此选择Nothing.然后它试图找到一个隐含的Nothing =>单元.因为没有这样的隐含,它就失败了.

从不会考虑print2返回的函数的参数来帮助进行类型推断.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读