美文网首页
Scala的7种值类型和条件表达式以及for循环

Scala的7种值类型和条件表达式以及for循环

作者: lehuai | 来源:发表于2018-01-03 09:55 被阅读0次
            Byte
        Char
        Short
        Int
        Long
        Float
        Double
    

    条件表达式

    scala> val x = 3
    x: Int = 3
    
    scala> val y = if ( x > 1 ) 1 else -1
    y: Int = 1
    
    scala> println(y)
    1
    
    scala> val z = if ( x > 1 ) 1 else "error"
    z: Any = 1
    
    scala> val z = if ( x < 1 ) 1 else "error"
    z: Any = error
    
    scala> val a = if ( x < 1 ) 1
    a: AnyVal = ()
    
    scala> val a = if ( x < 1 ) 1 else()
    a: AnyVal = ()
    
    scala> val b = if ( x > 1 ) 1 else if ( x < 1 ) -1 else 0
    b: Int = 1
    

    for循环

    scala> 1 to 10
    res1: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    
    scala> 1.to(10)
    res2: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    
    scala> 1 until 10
    res3: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)
    
    scala> for ( i <- 1 to 10 ) {
         | println(i)
         | }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    scala> val arr = Array("java","scala","python")
    arr: Array[String] = Array(java, scala, python)
    
    scala> for ( i <- arr ) println(i)
    java
    scala
    python
    
    scala> for ( i <- 1 to 3; j <- 1 to 3 if ( i != j  ) ) println( i * 10 + j)
    12
    13
    21
    23
    31
    32
    
    
    scala> for ( i <- 1 to 3 ) {
         | for ( j <- 1 to 3 ) {
         | if ( i != j ) println( i * 10 + j )
         | }
         | }
    12
    13
    21
    23
    31
    32
    scala> val res = for ( i <- 1 until 10 ) yield i
    res: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9)
    
    scala> println(res)
    Vector(1, 2, 3, 4, 5, 6, 7, 8, 9)
    
    scala> 1.+(3)
    warning: there were 1 deprecation warning(s); re-run with -deprecation for details
    res10: Double = 4.0
    
    

    相关文章

      网友评论

          本文标题:Scala的7种值类型和条件表达式以及for循环

          本文链接:https://www.haomeiwen.com/subject/pmzcnxtx.html