简体   繁体   English

Scala:当我使用“Option”时,为什么会出现类型不匹配错误?

[英]Scala: Why do I get a type mismatch error when I use “Option”?

I'm new to Scala. 我是Scala的新手。 I have a Scala function, and one of its arguments uses "Option": 我有一个Scala函数,其中一个参数使用“Option”:

def generateTimeSnippet(startOfSentence: Double, endOfSentence: Option[Double]): (Double, Option[Double]) = {
   ...
}

When I call this function, I give literal values to the arguments: 当我调用这个函数时,我给参数提供了文字值:

val snippets = generateTimeSnippet(startOfSentence = 10d, endOfSentence = 20.5)

But this results in a type mismatch error: "type mismatch; found : Double(10.0) required: Option[Double]" 但这会导致类型不匹配错误:“类型不匹配;找到:需要Double(10.0):选项[Double]”

I find this very odd. 我觉得这很奇怪。 Why is this happening? 为什么会这样? Am I not supposed to be allowed to use Doubles for an argument that is defined as Option[Double]? 我不应该被允许使用Doubles作为定义为Option [Double]的参数吗?

Of course, for an argument of the type Option[Double] , you can not send in the type Double . 当然,对于Option[Double]类型的参数,您不能发送Double类型。 They are different types. 它们是不同的类型。

You can send in Some(20.5) which is of the type Option[Double] 您可以发送Some(20.5)类型Option[Double]

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

相关问题 为什么在使用返回 Option[Long] 类型对象的 UDF 时会出现类型不匹配错误? - Why do I get a type mismatch error when using a UDF that returns an object of type Option[Long]? 为什么我在Scala Spark中得到类型不匹配的信息? - Why I get type mismatch in scala Spark? Scala泛型; 为什么会出现“类型不匹配,预期:T,实际T” - Scala generics; Why do I get 'Type mismatch, expected: T, actual T' 在从Option [A]中提取值时,如何让类型签名与scala编译器一致? - How do I get the type signature to agree with the scala compiler when extracting a value out of an Option[A]? 为什么我在 Scala 中收到 LocalDateTime 错误? - Why do I get LocalDateTime error in Scala? 我是否必须在Scala中初始化Option类型 - Do I have to initialize Option type in Scala 为什么会有“类型不匹配;为什么? 是否在Scala-IDE中找到了单位,期望为布尔值? - Why do I have “Type mismatch; Found Unit, expected Boolean” in Scala-IDE? 在我的 scala function 中,为什么会出现错误 - “类型不匹配;找到:所需单位:Int”? - In my scala function, why am I getting error - "type mismatch; found : Unit required: Int"? 为什么在“ for”表达式多生成器中出现类型不匹配 - Why I get type mismatch in “for” expression multigenerator Scala 为什么我的类型与 hashmap 不匹配? - Scala Why am I getting a type mismatch with hashmap?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM