简体   繁体   中英

Scala type mismatch [scala]

I have the following function

def weight(Actors:RDD[(String,Int)],name:String,count:Int):Float={
    val count1=Actors.lookup(name)
    val i_count=if (!count1.isEmpty) count1(0) else 0
    val edge=if (i_count!=0) (count.toFloat/i_count.toFloat) else 0.0   
}

and I get the following error

 <console>:229: error: type mismatch;
 found   : Unit
 required: Float
       }

Is it caused by divide 0 error? How to solve that problem?

The weight function is not returning anything but Float is defined as a return type.

Replacing the final line

val edge=if (i_count!=0) (count.toFloat/i_count.toFloat) else 0.0

by

if (i_count!=0) (count.toFloat/i_count.toFloat) else 0F

should resolve your issue

This error means your are return Unit for weight method, but def weight(Actors:RDD[(String,Int)],name:String,count:Int):Float is expecting return Float value of this method, so this compile error is throwed .

Solution:

@Ramesh Maharjan has provided a way to fix this. but also you can try pattern match in Scala , like:

i_count match {
  case 0 => 0.0F
  case _=> count.toFloat/i_count.toFloat
}

No, it's not related to division-by-zero. Defining a val as the last line in your function will be treated as returning type Unit . Changing it to the following will fulfill the Float return type you declared for the function:

if (i_count != 0) (count.toFloat / i_count.toFloat) else 0.toFloat

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.

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