scala--控制结构

for i <- List(1, 2, 3) do println(i)

for
i <- 1 to 10
if i > 3
if i < 6
do
println(i)

val listOfInts = for
i <- 1 to 10
if i > 3
if i < 6
yield
i * 10

def isTrue(a: Matchable): Boolean = a match
case 0 | “” => false
case _ => true

def toInt(s: String): Option[Int] =
try
Some(s.toInt)
catch
case e: NumberFormatException => None

try
// some exception-throwing code here
catch
case e1: Exception1Type => // handle that exception
case e2: Exception2Type => // handle that exception
finally
// close your resources and do anything else necessary here

(i: @switch) match {
case 0 => println(“Sunday”)
case 1 => println(“Monday”)
case 2 => println(“Tuesday”)
case 3 => println(“Wednesday”)
case 4 => println(“Thursday”)
case 5 => println(“Friday”)
case 6 => println(“Saturday”)
// catch the default with a variable so you can print it
case whoa => println(s"Unexpected case: ${whoa.toString}")

def test(x: Matchable): String = x match

// constant patterns
case 0 => "zero"
case true => "true"
case "hello" => "you said 'hello'"
case Nil => "an empty List"

// sequence patterns
case List(0, _, _) => "a 3-element list with 0 as the first element"
case List(1, _*) => "list, starts with 1, has any number of elements"

// tuples
case (a, b) => s"got $a and $b"
case (a, b, c) => s"got $a, $b, and $c"

// constructor patterns
case Person(first, "Alexander") => s"Alexander, first name = $first"
case Dog("Suka") => "found a dog named Suka"

// typed patterns
case s: String => s"got a string: $s"
case i: Int => s"got an int: $i"
case f: Float => s"got a float: $f"
case a: Array[Int] => s"array of int: ${a.mkString(",")}"
case as: Array[String] => s"string array: ${as.mkString(",")}"
case d: Dog => s"dog: ${d.name}"
case list: List[_] => s"got a List: $list"
case m: Map[_, _] => m.toString

// the default wildcard pattern
case _ => "Unknown"

end test

sealed trait Animal
case class Dog(name: String) extends Animal
case class Cat(name: String) extends Animal
case object Woodpecker extends Animal

def getInfo(a: Animal): String = a match
case Dog(moniker) => s"Got a Dog, name = $moniker"
case _: Cat => “Got a Cat (ignoring the name)”
case Woodpecker => “That was a Woodpecker”

import scala.io.Source
import java.io.{FileNotFoundException, IOException}
def readFile(filename: String): Option[String] =
try
Some(Source.fromFile(filename).getLines.mkString)
catch
case _: (FileNotFoundException|IOException) => None

@throws(classOf[NumberFormatException])
def readFile(filename: String): String =
try
Source.fromFile(filename).getLines.mkString
catch
case t: Throwable => throw t
scala建议不要跑出异常,用option代替
import scala.io.Source
import java.io.{FileNotFoundException, IOException}
import scala.util.{Try,Success,Failure}
def readFile(filename: String): Try[String] =
try
Success(Source.fromFile(filename).getLines.mkString)
catch
case t: Throwable => Failure(t)

import scala.util.control.Exception.allCatch

// OPTION
allCatch.opt(“42”.toInt) // Option[Int] = Some(42)
allCatch.opt(“foo”.toInt) // Option[Int] = None

// TRY
allCatch.toTry(“42”.toInt) // Matchable = 42
allCatch.toTry(“foo”.toInt)
// Matchable = Failure(NumberFormatException: For input string: “foo”)

// EITHER
allCatch.either(“42”.toInt) // Either[Throwable, Int] = Right(42)
allCatch.either(“foo”.toInt)
// Either[Throwable, Int] =
// Left(NumberFormatException: For input string: “foo”)

尽量别使用null
var store: Store = null
var inbox: Folder = null
try
store = session.getStore(“imaps”)
inbox = getFolder(store, “INBOX”)
// rest of the code here …
catch
case e: NoSuchProviderException => e.printStackTrace
case me: MessagingException => me.printStackTrace
finally
if (inbox != null) inbox.close
if (store != null) store.close
可以换成
import scala.io.Source
import java.io.*
var sourceOption: Option[Source] = None
try
sourceOption = Some(Source.fromFile("/etc/passwd"))
sourceOption.foreach { source =>
// do whatever you need to do with ‘source’ here …
for line <- source.getLines do println(line.toUpperCase)
}
catch
case ioe: IOException => ioe.printStackTrace
case fnf: FileNotFoundException => fnf.printStackTrace
finally
sourceOption match
case None =>
println(“bufferedSource == None”)
case Some(s) =>
println(“closing the bufferedSource …”)
s.close

import scala.annotation.tailrec
object WhileTrue:
@tailrec
def whileTrue(testCondition: => Boolean)(codeBlock: => Unit): Unit =
if (testCondition) then
codeBlock
whileTrue(testCondition)(codeBlock)
end if
end whileTrue

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值