简体   繁体   English

Scala中的编译错误 - 类型不匹配

[英]compilation error in Scala - type mismatch

This`s compile without problem : 这个编译没有问题:

class Tweet(val user: String, val text: String, val retweets: Int) { 
  override def toString: String = "User: " + user + "\n" + "Text: " + text + " [" + retweets + "]" 
}

var max: Tweet = elem
def most(cur: Tweet) {
  if (cur.retweets > max.retweets) max=cur
}
foreach(most( _ ))

But this not compile : 但这不编译:

var max: Tweet = elem
foreach( if ( _.retweets > max.retweets) max=_ )

Why ? 为什么?

I got this error: 我收到了这个错误:

Error:(157, 19) missing parameter type for expanded function ((x$1) => x$1.retweets.$greater(max.retweets))
    foreach( if ( _.retweets > max.retweets) max=_ )

Error:(157, 14) type mismatch;
 found   : Unit
 required: objsets.Tweet => Unit
    foreach( if ( _.retweets > max.retweets) max=_ )

The reason for that, is that each underscore refers to the next argument, so for instance, if you have a function defined like this: 原因是每个下划线都引用下一个参数,例如,如果你有一个像这样定义的函数:

def foo(f: (Int, Int) => Int)

You can use anonymous function using exactly two underscores: 您可以使用正好两个下划线的匿名函数:

// Valid:
foo(_ + _)

// Invalid:
foo(_ + 1)
foo(_ + _ + _)

So in your example, if you want to reuse the argument in the closure given to foreach function, you must call it this way: 因此,在您的示例中,如果要在foreach函数的闭包中重用参数,则必须以这种方式调用它:

foreach(i => if (i.retweets > max.retweets) max = i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM