以更实用的风格更改 if-else 结构?

发布于 2024-12-13 08:00:36 字数 399 浏览 4 评论 0原文

是否有可能以更实用的 Scala 风格更改此 if-else 结构?

def getMIMEType(document: String): String = {

  if (document.endsWith(".pdf")) {
    return "application/pdf"
  } else if (document.endsWith(".dxf")) {
    return "application/dxf"
  } else if (document.endsWith(".jpg")) {
    return "image/jpeg"
  } else return "application/octet-stream"
}

我尝试使用模式匹配,但它不起作用。所以我很好奇一个好的解决方案。

is it possible to change this if-else-construct in a more functional style of Scala?

def getMIMEType(document: String): String = {

  if (document.endsWith(".pdf")) {
    return "application/pdf"
  } else if (document.endsWith(".dxf")) {
    return "application/dxf"
  } else if (document.endsWith(".jpg")) {
    return "image/jpeg"
  } else return "application/octet-stream"
}

I tried to use pattern matching, but it doesn't work. So I be curious for a good solution.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

沐歌 2024-12-20 08:00:36

MIME 类型映射

我同意@glowcoder。我发现至少在这种特殊情况下,最好使用 MIME 类型映射。这是一个 Scala 版本:

val MimeTypesMapping = Map(
  ".pdf" -> "application/pdf",
  ".dxf" -> "application/dxf",
  ".jpg" -> "image/jpeg"
)

def extension(fileName: String) = fileName substring (fileName lastIndexOf ".")

def getMIMEType(document: String) =
  MimeTypesMapping get extension(document) getOrElse "application/octet-stream"

此外,正如 Rex Kerr 所指出的,您可以直接将默认值添加到映射定义中:

val MimeTypesMapping = Map(
  ".pdf" -> "application/pdf",
  ".dxf" -> "application/dxf",
  ".jpg" -> "image/jpeg"
) withDefaultValue "application/octet-stream" 

然后像这样使用它: MimeTypesMapping(extension(document))

模式匹配

如果您不这样做不像第一个解决方案,那么您可以使用模式匹配来代替:

def getMIMEType(document: String) = extension(document) match {
  case ".pdf" => "application/pdf"
  case ".dxf" => "application/dxf"
  case ".jpg" => "image/jpeg"
  case _      => "application/octet-stream"
}

此解决方案的优点是您可以在条件中进行更复杂的逻辑,例如:

def getMIMEType(document: String) = extension(document) match {
  // ...
  case ".jpg" | ".jpeg" => "image/jpeg"
  // ...
}

使用自定义提取器进行模式匹配

还有另一种使用模式匹配的方法。您可以为文件扩展名编写自己的提取器,然后在 match 中使用它:

object Extension {
  def unapply(fileName: String): Option[String] = {
    val idx = fileName lastIndexOf "."

    if (idx != -1) Some(fileName substring idx) else None
  }
}

def getMIMEType(document: String) = document match {
  case Extension(".pdf") => "application/pdf"
  case Extension(".dxf") => "application/dxf"
  case Extension(".jpg") => "image/jpeg"
  case _                 => "application/octet-stream"
}

MIME-Type mapping

I agree with @glowcoder. I find that at least in this particular case it's better to have MIME-Types mapping. Here is a Scala version:

val MimeTypesMapping = Map(
  ".pdf" -> "application/pdf",
  ".dxf" -> "application/dxf",
  ".jpg" -> "image/jpeg"
)

def extension(fileName: String) = fileName substring (fileName lastIndexOf ".")

def getMIMEType(document: String) =
  MimeTypesMapping get extension(document) getOrElse "application/octet-stream"

Also, as Rex Kerr noted, you can add default value directly to the mapping definition:

val MimeTypesMapping = Map(
  ".pdf" -> "application/pdf",
  ".dxf" -> "application/dxf",
  ".jpg" -> "image/jpeg"
) withDefaultValue "application/octet-stream" 

and then use it like this: MimeTypesMapping(extension(document))

Pattern Matching

If you don't like first solution, then you can use pattern matching instead:

def getMIMEType(document: String) = extension(document) match {
  case ".pdf" => "application/pdf"
  case ".dxf" => "application/dxf"
  case ".jpg" => "image/jpeg"
  case _      => "application/octet-stream"
}

Advantage of this solution is that you can can more sophisticated logic in the conditions like for example:

def getMIMEType(document: String) = extension(document) match {
  // ...
  case ".jpg" | ".jpeg" => "image/jpeg"
  // ...
}

Pattern Matching with Custom Extractor

There is also another way to use pattern matching. You can write your own extractor for the file extension an then use it in match:

object Extension {
  def unapply(fileName: String): Option[String] = {
    val idx = fileName lastIndexOf "."

    if (idx != -1) Some(fileName substring idx) else None
  }
}

def getMIMEType(document: String) = document match {
  case Extension(".pdf") => "application/pdf"
  case Extension(".dxf") => "application/dxf"
  case Extension(".jpg") => "image/jpeg"
  case _                 => "application/octet-stream"
}
情话墙 2024-12-20 08:00:36

我不知道 scala 的内置结构到底是什么,但听起来你想要一张地图。就像,Java 使用

val map = scala.collection.mutable.HashMap[String, String]()
map.put(".pdf","application/pdf");
map.put(".dxf","application/dxf");
map.put(".jpg","image/jpeg");

Then 在你的函数中使用

def ext = getExtension(document); // assume this exists, eh?
if(map.containsKey(ext)) return map.get(ext);
return "application/octet-stream";

Update:看起来 Scala 使用了一个非常相似的映射:

http://www.scala-lang.org/api/rc/scala/collection/mutable/Map.html

I don't know exactly what scala's built in structures are, but it sounds like you want a map. Like, Java uses

val map = scala.collection.mutable.HashMap[String, String]()
map.put(".pdf","application/pdf");
map.put(".dxf","application/dxf");
map.put(".jpg","image/jpeg");

Then in your function you use

def ext = getExtension(document); // assume this exists, eh?
if(map.containsKey(ext)) return map.get(ext);
return "application/octet-stream";

Update: It looks like Scala uses a map that's very similar:

http://www.scala-lang.org/api/rc/scala/collection/mutable/Map.html

岁月如刀 2024-12-20 08:00:36

除了我上面的评论之外,我还想对其进行优化,使其实际上成为 scala。

    def getMIMEType(document: String): String = {

        if (document endsWith ".pdf") {
             return "application/pdf"
        } 
        if (document endsWith ".dxf") {
             return "application/dxf"
        } 
        if (document endsWith ".jpg") {
             return "image/jpeg"
        } 
             "application/octet-stream"
    }

我在这里看到代码不能同时满足两个条件中的任何一个。所以我建议使用上面的代码。另外,如果对于最后一个返回语句,即“application/octet-stream”,您可以使用适当的“if条件”,如果您找出最后一行的“if”,则可以删除所有返回,否则上面的代码很好。

返回类型也无需提及。

    def getMIMEType(document: String): String = {} 

可以写为,

    def getMIMEType(document: String) = {} 

检查它是否适合您。

Along with my above comment i would like to optimize it to make it scala in actual.

    def getMIMEType(document: String): String = {

        if (document endsWith ".pdf") {
             return "application/pdf"
        } 
        if (document endsWith ".dxf") {
             return "application/dxf"
        } 
        if (document endsWith ".jpg") {
             return "image/jpeg"
        } 
             "application/octet-stream"
    }

I See here that the code cannot satisfy any of two conditions at a time. So i would suggest the above code to be used. Also if for the last return statement i.e "application/octet-stream" u can use a proper "if condition", if u figure out the "if" for the last line then all the returns can be removed else the above code is good.

Also the return type need not be mentioned.

    def getMIMEType(document: String): String = {} 

can be written as,

    def getMIMEType(document: String) = {} 

check for this if it works for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文