Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Zad2

class Euro(eu: Int, cen: Int = 0) {
  var euro: Int = eu
  var cents: Int = cen
  var inCents: Int = (euro * 100) + cents

  def +(x: Euro): Unit = {
    val a = x.cents + cents
    val b = x.euro + euro + (a / 100)
    cents = a % 100
    euro = b
  }

  def *(x: Int): Unit = {
    val a = cents*x
    val b = euro*x + (a/100)
    cents = a % 100
    euro = b
  }
}

object Euro {
  def fromCents(cents: Int): Euro = {
    new Euro(cents / 100, cents % 100)
  }
}

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println("hellooo")
  }

  def f(e: Euro): Unit = {
    println(e.euro + "." + e.cents)
  }
}

SCALA

//Scala é uma linguagem compilada, então antes de executar o código, é necessário compilar o arquivo

//Define uma classe
object HelloWorld {
    //Inicio do main    
   def main(args: Array[String]) {
      //É necessário o println() da expressão aritmética pois diferentemente do Clojure 
      //o resultado não é retornado no final
      //println("Resultado Aritmético " ++ ((1 + 2) * 3))
      
      //Strings podem ser concatenadas com '++'
      println("Hello, " ++ "Scala!")

      //Podem ser utilizados métodos, que são chamados com .nomeMetodo e não são necessários os ( ) caso não sejam utilizados argumentos
      println("Hello, Scala".size)
      println("Hello, Scala".toUpperCase)
      println("foo".drop(1))
      println("bar".take(2))
      println(1.to(10))
      println((0 until 10).contains(10))


      //Operadores são métodos com nomes simbólicos
      //Expressões aritméticas podem também ser escritas como abaixo
      println(3.+(2))

      //Como a linguagem é compilada, os tipos serão verificados, então expressões como a abaixo geram erro
      //1.to("5")
      
      //Declaração de variáveis 
      //Sintaxe:
      //val ou var nomeDaVariavel : DataType = [valor]

      var minhaVariavel  = "sou mutável"

      val minhaVariavel2 = "sou imutável" 
      println(minhaVariavel)
      //Associação múltipla
      //Se um bloco de código ou um método retornar uma Tupla, esta tupla poderá ser associada a uma variável
      //val (myVar1: Int, myVar2: String) = Pair(40, "Foo")



   }
}

Compile and Execute Scala Online

object HelloWorld {
    
   case class Book(title: String, yearPublished: Integer, author: String, isbn: String)
   
   val progInScala = Book("Programming in Scala 3rd Edition", 2016, "Martin Odersky", "0981531687")
   val funcProgInScala = Book("Functional Programming in Scala", 2014, "Paul Chiusano", "1617290653")
   val scalaCookbook = Book("Scala Cookbook", 2013, "Alvin Alexander", "1449339611")
   
   val matchCase = progInScala match {
       case Book(title, yearPublished, author, isbn) => println(s"$title <=> $yearPublished <=> $author <=> isbn")
       case _ => println("Did not match anything!")
   }
   
   val authMatch = progInScala match {
       case Book(_, yearPublished, _, _) => println(yearPublished)
       case _ => "No Author!"
   }
    
   def main(args: Array[String]) {
       val number = 10
       
       val isMatch = number match {
           case 0 => "Zero"
           case 5 => "Five"
           case 9 => "Nine"
           case _ => "No matches!"
       }
       
       println(isMatch)
   }
}

s14616 kolokwium

object HelloWorld {
   def main(args: Array[String]) {
      def pow[T](l: Vector[T], w: T => Boolean): Vector[T] = l.reverse.filterNot(w)
      val z1 = pow[Int](Vector(0, 1, 1, 2), num => {if(num%2 != 0) true else false})
      z1.foreach(println)
      println
      val z2 = pow[Char](Vector('a','b','c','d'), let => {if(let=='b')true else false})
      z2.foreach(println)}
      
      def frq(l: String) : Map[Char, Int] = {
        l.groupBy(identity).mapValues(_.size)
      }
      println(frq("Abba"))
}

s14616 kolokwium

object HelloWorld {
   def main(args: Array[String]) {
      def pow[T](l: Vector[T], w: T => Boolean): Vector[T] = l.reverse.filterNot(w)
      val z1 = pow[Int](Vector(0, 1, 1, 2), num => {if(num%2 != 0) true else false})
      z1.foreach(println)
      println
      val z2 = pow[Char](Vector('a','b','c','d'), let => {if(let=='b')true else false})
      z2.foreach(println)}
      
      def frq(l: String) : Map[Char, Int] = {
        l.groupBy(identity).mapValues(_.size)
      }
      println(frq("Abba"))
} 

Scala Labs

object HelloWorld {
   def main(args: Array[String]) {
      println("Hello, world!")
   }
}

Compile and Execute Scala Online

Object Order
{
   
   
    // Define static method with return type Order
    def apply(item: String, qty: String, price: String): Order = 
    {
        new Order(item: String, qty: String, price: String);
    }
}

/*******************
 *  Order Blueprint
 *******************/
 
class Order(item: String, qty: String, price: String){
 
 override def toString = "Product: "+ item + "\nQuantity: " + qty + "\nUnitPrice: "+ price +" \nTotalPrice: ?";
 
}

ScalaAssignment

//Question 1
implicit def toInt(value: String): Int = value.toInt
implicit def toString(student: Student): String = student.name
case class Student(id:Int, name:String)

val studentName:String = Student("10","John Dole")





//Question 2
implicit def toList(marks: Marks): List[Int] = marks.marks
case class Marks(course:String, marks:List[Int])

def totalMarks(marks: List[Int]):Int = marks.sum

val marks = List(80,50,100,30)

totalMarks(Marks("FunctionalProgramming",marks))

//Question 3
case class Course(subjects:List[String])

def getNumberofSubjects(course:Course):Int = course.subject.size

getNumberofSubjects


//Question 4
implicit class greetTheWorld(helloWorld: HelloWorld){
    
    def greetTheWorld = helloworld.greeting
}
class HelloWorld{
    def greeting ="Greeting from hello World"
    
    val getGreeting = new HelloWord().greetTheWorld
}

Compile and Execute Scala Online

object HelloWorld {
    
    def main(args: Array[String]){
        
        println("Hello, World!");
    }
}

Compile and Execute Scala Online

  import java.math.BigInteger
  import scala.collection.mutable.Map
  import scala.collection.mutable.Set
  object HelloWorld {
     def main(args: Array[String]) {
     def max2(x: Int, y: Int) = if (x > y) println(x) else println(y)
       max2(4,5);
         println("Hello, "+ args(0) +"!")
         var res: Int = 5;
         res = res * 3
         println(res)
         def greet() = println("Hello, world!")
         greet();
           var i = 0
            while (i < args.length) {
             println(args(i))
            i += 1
            } 
            var j = 0
        while (j < args.length) {
            if (j != 0)
             print(" ")
                print(args(j))
                j += 1
            }
         println()
         args.foreach(arg => println(arg))
         args.foreach((arg: String) => println(arg))
          args.foreach(println)
           for (arg <- args)
             println(arg)
               val big = new java.math.BigInteger("12345")
               println(big)
    
  val greetStrings = new Array[String](3)
    greetStrings(0) = "Hello"
  greetStrings(1) = ", "
  greetStrings(2) = "world!\n"
  for (i <- 0 to 2)
    print(greetStrings(i))
  greetStrings.update(0, "Hello")
  greetStrings.update(1, ", ")
  greetStrings.update(2, "world!\n")
  for (i <- 0.to(2))
    print(greetStrings.apply(i))
    greetStrings(0) = "Hello" 
    greetStrings.update(0, "Hello")
    println(greetStrings(0))
    val numNames = Array("zero", "one", "two")
    val numNames2 = Array.apply("zero", "one", "two")
         val oneTwo = List(1, 2)
  val threeFour = List(3, 4)
  val oneTwoThreeFour = oneTwo ::: threeFour
  println(""+ oneTwo +" and "+ threeFour +" were not mutated.")
  println("Thus, "+ oneTwoThreeFour +" is a new list.")
   val twoThree = List(2, 3)
   val oneTwoThree = 1 :: twoThree
   println(oneTwoThree)
 val oneTwoThreee = 1 :: 2 :: 3 :: Nil
  println(oneTwoThreee)
   val pair = (99, "Luftballons")
        println(pair._1)
        println(pair._2)
        var jetSet = Set("Boeing", "Airbus")
  jetSet += "Lear"
  println(jetSet.contains("Boeing"))
    val movieSet = Set("Hitch", "Poltergeist")
  movieSet += "Shrek"
  println(movieSet) 
    val treasureMap = Map[Int, String]()
  treasureMap += (1 -> "Go to island.")
  treasureMap += (2 -> "Find big X on ground.")
  treasureMap += (3 -> "Dig.")
  println(treasureMap(2))
  val romanNumeral = Map(
    1 -> "I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V"
  )
  println(romanNumeral(4))
  def printArgs(args: Array[String]): Unit = {
    args.foreach(println)
              }
              printArgs(Array("zero", "one", "two"))
       def printArgs1(args: Array[String]): Unit = {
            var i = 0
            while (i < args.length) {
                  println(args(i))
             i += 1
               }
          }
     printArgs1(Array("zero", "one", "two"))  
     def printArgs2(args: Array[String]): Unit = {
    for (arg <- args)
      println(arg)
  }
        printArgs2(Array("zero", "one", "two"))  
         def printArgs3(args: Array[String]): Unit = {
        args.foreach(println)
  }
          printArgs3(Array("zero", "one", "two"))  
           def formatArgs(args: Array[String]) = args.mkString("\n")
            println(formatArgs(args))
     val res1 = formatArgs(Array("zero", "one", "two"))
        assert(res1 == "zero\none\ntwo")
       }
  }

Previous 1 ... 4 5 6 7 8 9 10 ... 13 Next
Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.