Save
Busy. Please wait.
Log in with Clever
or

show password
Forgot Password?

Don't have an account?  Sign up 
Sign up using Clever
or

Username is available taken
show password


Make sure to remember your password. If you forget it there is no way for StudyStack to send you a reset link. You would need to create a new account.
Your email address is only used to allow you to reset your password. See our Privacy Policy and Terms of Service.


Already a StudyStack user? Log In

Reset Password
Enter the associated with your account, and we'll email you a link to reset your password.
focusNode
Didn't know it?
click below
 
Knew it?
click below
Don't Know
Remaining cards (0)
Know
0:00
Embed Code - If you would like this activity on your web page, copy the script below and paste it into your web page.

  Normal Size     Small Size show me how

Scala

Tipos e métodos genéricos, Tuplas e funções como objetos

ConceitoExemplo
Classes em Scala podem ser tipos como parâmetros. abstract class IntStack { def push(x: Int): IntStack = new IntNonEmptyStack(x, this) def isEmpty: Boolean def top: Int def pop: IntStack }
Usando classes genéricas. val x = new EmptyStack[Int] val y = x.push(1).push(2) println(y.pop.top)
Generalizar classes genéricas. Como exemplo a classe IntSet: abstract class Set[A] { def incl(x: A): Set[A] def contains(x: A): Boolean }
Função para retornar o quociente inteiro e o resto de dois argumentos inteiros. def divmod(x: Int, y: Int) = new Tuple2[Int, Int](x / y, x % y)
O programa é funcional. def prime(x : Int) : Boolean = 2.to(x-1).filter(x % _ == 0).isEmpty println(prime(1)) println(prime(5)) println(prime(9)) println(prime(11))
Listas criadas e manipuladas. var arr = for(i <- 0 to 20 if i % 2 == 0) yield i arr.foreach(println)
Em Scala, funções também são objetos, possibilitando passar funções como argumentos e outras funcionalidades. object Timer { def oncePerSecond(callback: () => unit) { while (true) { callback(); Thread sleep 1000 } } def timeFlies() { println("o tempo corre como um raio...") } def main(args: Array[String]) { oncePerSecond(timeFlies) } }
Uma função pode ser definida apenas para ser passada como parâmetro para outra função, sendo desnecessário este procedimento, existe a possibilidade de construir a função diretamente, utilizando função anônima. object TimerAnonymous { def oncePerSecond(callback: () => unit) { while (true) { callback(); Thread sleep 1000 } } def main(args: Array[String]) { oncePerSecond(() => println("o tempo corre como um raio...")) } }
As classes em Scala podem ter parâmetros. class Complex(real: Double, imaginary: Double) { def re() = real def im() = imaginary }
Quando não é informada de qual super-classe uma classe deverá ser herdada, é utilizado por padrão 'scala.Object'. Conforme consta no exemplo abaixo, não foi informado a super-classe, por isso, automaticamente foi usado o padrão 'scala.Object': class Complex(real: Double, imaginary: Double) { def re = real def im = imaginary }
Pode haver um membro abstrato que é um tipo e um que é valor. abstract class AbsCell { type T; val init: T; private var value: T = init; def get: T = value; def set(x: T): unit = { value = x } } val cell = new AbsCell { type T = int; val init = 1 }
A abstração da classe e argumentos é realizada através de parâmetros que são tipos. def swap[T](x: GenCell[T], y: GenCell[T]): unit = { val t = x.get; x.set(y.get); y.set(t) }
Tanto em membros abstratos quanto em genéricos, é possível restringir as especializações que poderão ser usadas. abstract class Ordered { type O; def < (that: O): boolean; def <= (that: O): boolean = this < that || this == that } abstract class MaxCell extends AbsCell { type T <: Ordered { type O = T } def setMax(x: T) = if (get < x) set(x) }
É possível escrever Scala dentro do XML. val labPhoneBook = <phonebook> <descr>Phone numbers of<b>XML</b> hackers.</descr> <entry> <name>Burak</name> <phone where="work"> +41 21 693 68 67 </phone> <date> { df.format(new java.util.Date()) } </date> </entry> </phonebook>;
Objeto future, representa um valor que ainda não foi retornado por uma mensagem assíncrona. import scala.actors.Futures._ val eventualmente = future(5 * 42) println(eventualmente())
A linguagem Scala possui o reaproveitamento de threads, sendo assim, se cada ator em um programa usar react, apenas uma única thread será necessária. def act() { loop { react { case (name: String, actor: Actor) => actor ! getIp(name) case msg => println("Mensagem: " + msg)
é possível criar Scripts Shell utilizando Scala, através de um arquivo '.bat'. ::#! @echo off call scala %0 %* goto :eof ::!# Console.println("Hello, world!") argv.toList foreach Console.println
Os Iteradores permitem que se ande somente um passo na sequência de cada vez, através de métodos abstratos. trait Iterator[+A] { def hasNext: Boolean def next: A
Recurso de interação [cce] args.foreach(arg => println(arg)) [/cce]
A sintaxe de declaração de função é simples. def (parâmetros) =
Created by: Bru
Popular Computers sets

 

 



Voices

Use these flashcards to help memorize information. Look at the large card and try to recall what is on the other side. Then click the card to flip it. If you knew the answer, click the green Know box. Otherwise, click the red Don't know box.

When you've placed seven or more cards in the Don't know box, click "retry" to try those cards again.

If you've accidentally put the card in the wrong box, just click on the card to take it out of the box.

You can also use your keyboard to move the cards as follows:

If you are logged in to your account, this website will remember which cards you know and don't know so that they are in the same box the next time you log in.

When you need a break, try one of the other activities listed below the flashcards like Matching, Snowman, or Hungry Bug. Although it may feel like you're playing a game, your brain is still making more connections with the information to help you out.

To see how well you know the information, try the Quiz or Test activity.

Pass complete!
"Know" box contains:
Time elapsed:
Retries:
restart all cards