FAQ Database Discussion Community


The right encoding for `URLEncoder.encode`

java,scala,urlencode,url-encoding
I am trying to standardize the messages in my URLs and I am using URLEncoder.encode. The problem I get is that, the output does not seem to be a valid url. For example val text = Some("test question (a) x (b) y").get val query = "http://localhost:8080/ask?text=" + text println(query) val...

Scala - Option Type Var Manipulation

scala,scala-option
I am working on an online exercise practicing Options and threads, both of which I have very little experience. The online exercise comes with a test suite, so right now I am trying to get my Option test cases to pass before I move on to the thread test cases....

How to search for an Exchange appointment for an iCalUid using Java EWS API?

java,scala,ews,exchange-server-2010,ewsjavaapi
I am using the Java EWS library to search for appointments in a user's calendar by iCalUid (example iCalUid I have: 040000008200E00074C5B7101A82E00800000000F66E2C0D59A9D001000000000000000010000000F7A6AACB779B00429164F39AE6DD6BB9). Here is my Scala code: import microsoft.exchange.webservices.data._ import java.net.URI import java.util.Date val exchange = { val service = new ExchangeService(ExchangeVersion.Exchange2010_SP2) service.setUrl(new URI(host)) service.setCredentials(new WebCredentials(user, pass)) service } def...

Regex Extraction in Scala

regex,scala
I have a text file that has some data like this :- 1/4 cup chopped green onion 1/2 teaspoon salt 1 Tbsp cream 1 teaspoon vanilla extract I want to write a regexp such that my data is divided into groups of 3 like below:- '1/4' 'çup' 'chopped green onion'...

Listing Scala nested objects methods through Reflection

scala,reflection
I have the following Scala object: object BusinessFacade { /** * Fachada para acesso aos métodos de controle de Usuário */ object Usuario { private lazy val usuarioBC = new UsuarioBC def buscar(id: Long)(implicit s: Session) = { usuarioBC.findById(id) } def inserir(usuario: User)(implicit s: Session) = { usuarioBC.insert(usuario) } def...

refer to scala function by name?

scala
Here is another stupid scala question regarding functions as first class objects in Scala. I'm very sorry if this is a repeat, as it probably is. In Python, Lisp, Perl, Scheme, etcetera I'm used to creating function values and assigning them names and passing them around to other functions, like...

Akka consolidate concurrent database requests

scala,akka,spray
I want to be able to make concurrent requests to multiple data repositories and consolidate the results. I am trying to understand if my approach is at all valid or if there is a better way to approach this problem. I am definitely new to Akka / Spray / Scala...

Specs2 with Futures and Case Classes

scala,future,specs2
I have a lot of problems working with futures as an answer of using Scala Dispatch for asynchronous HTTP calls. I also used Case Class Matchers lets suppose that I make a call here: http://ip.jsontest.com/ wich returns this json: { "ip": "x.xxx.xxx.xxx" } so I build my Specification as this...

Convert existing SBT Scala application to Play

scala,playframework,sbt,akka
I've been working on building an application with Akka actors, and now that I've completed the actor-based business logic I'd like to give it a RESTful + websocket front-end. I'm trying to find instructions for how to setup Play within the context of an existing application. The only instructions I...

IntelliJ - use imported modules as dependencies like maven projects in Eclipse

eclipse,scala,maven,intellij-idea,sbt
I've been asking myself this question for a couple of years but never really found the solution. I used to work with eclipse (on maven java projects). I could import a project -let's call it 'proj-A'- and if one of proj-A's dependencies was found in the workspace with the same...

Specify plugins in Build.scala

scala,sbt
If I want to use a build.scala file in order to build my project (instead of build.sbt) how do I specify the plugins? I want to use the sbt-assmbly plugin. and I am aware that I can create a plugins.sb file and do a addSbtPlugin there. But i want to...

How does Scala specs2 sequential keyword work

scala
As you know in scala you can do something like this : @RunWith(classOf[JUnitRunner]) class ApplicationSpec extends Specification { sequential } And tests will be ran sequentially. However, I dont understand this language wise. What kind of a variable(?) is sequential? It is just a single word hanging there, how does...

Spray route get response from child actor

scala,akka,spray
I am trying to figure out how I can setup a Master Actor that calls the appropriate children, in support of some spray routes where I am trying to emulate db calls. I am new to akka / spray, so just trying to gain a better understanding of how you...

PlayFramework: value as is not a member of Array[Byte]

scala,playframework
I want to make file download from a database using Play framework. But when I use this code I get this message: value as is not a member of Array[Byte] And if I change Ok(bytOfImage.as("image/jpg")) to Ok(bytOfImage) it works good but I get a file with a name: secondindex without...

Scala function partial application

scala,partialfunction
I'm trying to understand how function partial application works in Scala. To do that, I've built this simple code: object Test extends App { myCustomConcat("General", "Public", "License") foreach print GeneralPublicLicenceAcronym(myCustomConcat(_)) foreach print def myCustomConcat(strings: String*): List[Char] = { val result = for (s <- strings) yield { s.charAt(0) } result.toList...

Operand order in Scala List.prepend (::)

list,scala,operators
Odersky has brilliantly optimized Java syntax, enabling object calls without dots and parenthesis. I.e. instead of list.prepend(item), you now simply write list :: item, which also turns language operators into simple object methods. Here, List defines :: (prepend) operator. However, you normally write it vice-verse in Scala, using item ::...

Scala string replacement of entire words that comply with a pattern

string,scala,scala-collections,scala-string
In a string, how to replace words that start with a given pattern ? For instance replace each word that starts with "th", with "123", val in = "this is the example, that we think of" val out = "123 is 123 example, 123 we 123 of" Namely how to...

How to convert Map values to a set in scala

scala
In a Map class of Scala, the keySet method returns the set of the Map keys. The collection of map values are not set (as two keys might refer to the same value, so it is a multi-set). The valuesIterator method of the Map class returns an iterator, which makes...

How to define a Regex in StandardTokenParsers to identify path?

regex,scala,parsing,lexical-analysis
I am writing a parser in which I want to parse arithmetic expressions like: /hdfs://xxx.xx.xx.x:xxxx/path1/file1.jpg+1 I want to parse it change the infix to postfix and do the calculation. I used helps from a part of code in another discussion as well. class InfixToPostfix extends StandardTokenParsers { import lexical._ def...

Profiling a scala spark application

scala,apache-spark
I would like to profile my spark scala applications to figure out the parts of the code which i have to optimize. I enabled -Xprof in --driver-java-options but this is not of much help to me as it gives lot of granular details. I am just interested to know how...

Passing a function foreach key of an Array

scala,apache-spark,scala-collections,spark-graphx
I have an array like that : val pairs: Array[(Int, ((VertexId, Seq[Int]), Int))] which generates this output : (11,((11,ArraySeq(2, 5, 4, 5)),1)) (11,((12,ArraySeq(7, 7, 8, 2)),1)) (11,((13,ArraySeq(5, 9, 8, 7)),1)) (1,((1,ArraySeq(1, 2, 3, 4)),1)) (1,((4,ArraySeq(1, 5, 1, 1)),1)) I want to build a Graph for each pairs._1. That means for...

Scala which data structure is most efficient for my intended operations?

scala,arraybuffer,listbuffer
I am running a dynamic programming function where I carry a list of strings throughout the process. Over time, I append new strings to the end of this list, and occasionally I may remove the last element. Right now I am currently using a mutable ListBuffer, doing += for the...

Shuffled vs non-shuffled coalesce in Apache Spark

scala,apache-spark,bigdata,distributed-computing
What is the difference between the following transformations when they are executed right before writing RDD to a file? coalesce(1, shuffle = true) coalesce(1, shuffle = false) Code example: val input = sc.textFile(inputFile) val filtered = input.filter(doSomeFiltering) val mapped = filtered.map(doSomeMapping) mapped.coalesce(1, shuffle = true).saveAsTextFile(outputFile) vs mapped.coalesce(1, shuffle = false).saveAsTextFile(outputFile)...

Intellij isn't catching non-exhaustive matches that use functions as guards

scala,intellij-idea
I found this block of code in our codebase: val appId: (String, Option[String]) = request.app match { case Some(app) if hasAppId(app) => (Constants.AppId, app.id) case None => (Constants.AppId, None) } hasAppId returns a boolean. Clearly this match is non-exhaustive, but there's no compiler warning for it. If I change the...

My Scala program won't print anything

scala
Basically I'm trying to write a program that has a list of books and authors and then prints 2 things out, res1, which should print the book titles of the authors that have the name "Andrei" in it and res2 that should print the book titles that have the string...

Zipping two arrays together with index in Scala?

arrays,scala,zip
I have two arrays populated with integers. They are the same size (val array1 and val array2). I want to fuse them together into tuples with their index as the third element. For example if we have val array1 = Array(5,2,6,2) and val array2 = Array(9,8,3,4) then I want to...

Scala - increasing prefix of a sequence

scala
I was wondering what is the most elegant way of getting the increasing prefix of a given sequence. My idea is as follows, but it is not purely functional or any elegant: val sequence = Seq(1,2,3,1,2,3,4,5,6) var currentElement = sequence.head - 1 val increasingPrefix = sequence.takeWhile(e => if (e >...

Do scala classes have “self” like Python?

python,scala,class
For example if I have object Solution { class myClass(A: Array[Int]){ val something: Int = A.length; val another: Int = something/2; val someName = "blah" ... ... Do these variables "exist" only for a particular instance of myClass or are they "class-wide" variables shared among all objects? If it's the...

Pattern Matching chooses the wrong case if used with ClassTag

scala,reflection,covariance
What is the connection between variance and ClassTags or TypeTags? I have two types T1 and T2, that are used as type params. case class T1() case class T2() I have an abstract class with an invariant type parameter and one subclass, if I want to check the type of...

Akka actorSelection vs actorOf Difference

scala,akka,actor
Is there a difference between these two? When I do: context.actorSelection(actorNameString) I get an ActorSelection reference which I can resolve using the resolveOne and I get back a Future[ActorRef]. But with an actorOf, I get an ActorRef immediately. Is there any other vital differences other than this? What might be...

How to un-nest a spark rdd that has the following type ((String, scala.collection.immutable.Map[String,scala.collection.immutable.Map[String,Int]]))

scala,cassandra,apache-spark
Its a nested map with contents like this when i print it onto screen (5, Map ( "ABCD" -> Map("3200" -> 3, "3350.800" -> 4, "200.300" -> 3) (1, Map ( "DEF" -> Map("1200" -> 32, "1320.800" -> 4, "2100" -> 3) I need to get something like this Case...

ScalaJson: Traversing JSValue structure (JSONPath syntax) where key might be one of two different strings

json,scala,playframework,playframework-2.0,jsonpath
I need to retrieve information from a JsValue that may be structured in a few different ways buy the specific values I'm looking for will always be under similar names. So for example I could have something like: { "name" : "Watership Down", "location" : { "lat" : 51.235685, "long"...

Scala try-catch not catching exception

scala,try-catch
As far as I understand, the following code snippet should execute fine. Stream("A", "").toIterable.map(_.head) throws an exception, which should be caught by the try block. import org.scalatest.FunSuite class TryCatchTest extends FunSuite { test("Try failure") { List(1).flatMap { _ => try { Stream("A", "").toIterable.map(_.head) } catch { case e: Throwable =>...

Solving maze with Backtracking

scala,backtracking,maze
I am trying to solve a maze with scala using backtracking. My problem is that I keep on getting StackOverflow errors. I have tried qite alot of things but I always end up with a StackOverflow. findStart() and the getWay() show two approaches I have used. I know that it...

Scala wrong forward reference

scala,functional-programming
I am working through some of the exercises in: Functional Programming in Scala specifically problem 5.2. The issue is that with the following code which I have pieced together from the answer key. sealed trait Stream[+A] { def take(n: Int): Stream[A] = this match { case Cons(hs, ts) if n...

SCALA: change the separator in Array

arrays,string,scala,delimiter
I have an Array like this. scala> var x=Array("a","x,y","b") x: Array[String] = Array(a, x,y, b) How do I change the separator comma in array to a :. And finally convert it to string like this. String = "a:x,y:b" My aim is to change the comma(separators only) to other separator(say,:), so...

Is complexity of scala.xml.RuleTransformer really exponential?

xml,scala,time-complexity
This is a follow-up to one of my previous posts. I tried to understand why the RuleTransformer performance is so poor. Now I believe that it is so slow because its complexity is O(2n), where n is the height of the input XML tree. Suppose I need to rename all...

Calling the default constructor in scala

scala
I have a class definition in scala class A(p1: Type1,p2: Type2){ def this(p1: Type1){ //my constructor this() this.p1 = somevalue } } what is the difference between 1. val a:A = new A //Is this same as A()?? 2. val a:A = new A(v1,v2) How come 1. gives a compile...

Difficulty with SBT

scala,sbt
I have started using scala sbt pretty recently. One thing which I find very difficult with SBT is to find the right dependency signature. for example, I am reading a blog which was written in 2014 and it says add the following libraryDependencies "net.liftweb" %% "lift-son" % "2.5+" "org.apache.httpcomponents" %%...

Retrieving TriangleCount

scala,apache-spark,spark-graphx
I'm trying to retrieve the amount of triangles from a graph using graphX. As I'm new to both Scala and graphX, I'm currently quite stuck. I'm creating a graph from an edgefile: 1 2 1 3 2 3 This should be 1 triangle. Next I'm using the build in function...

Scala factory method with generics

scala
I have a couple of objects for which I'm trying to write a factory method. Simplified, these are: case class a[a1,a2](j:a1, k:a2) {} case class b[b1,b2](j:b1, k:b2) {} I would like to create a method which would allow me to pass in the type, and get an instance of that...

How to use the Akka ask pattern without blocking

scala,asynchronous,akka,future
Hi I have a actor which is responsible for fetching data from a database, turning it into a list and sending it back to the sender. I am using the ask pattern to receive response from my actor, because I don't want to use await.result because this approach will block...

Error while Parsing json into scala case class

java,scala,jackson,case-class
In my spring(mvc) web application, I am using org.codehaus.jackson.map.ObjectMapper in my scala code to map my json to scala objects using case classes. My Json String is an array of json objects objects. so I am using: val user = mapper.readValue(myJson, classOf[List[MyClass]]) This line throws an error: Exception in thread...

Scala child class fails to recognize a generic map in the parent?

scala,inheritance
I have the a code snippet which looks as follows: abstract class MultipleOutputWriter { protected def writers: collection.mutable.Map[Any, OutputStream] def write(basePath: String, value: Any) def close = writers.values.foreach(_.close) } class LocalMultipleOutputWriter extends MultipleOutputWriter { protected val writers = collection.mutable.Map[String, FileOutputStream]() def write(key: String, value: Any) = { //some implementation }...

scala minecraft forgemod 'gradle runClient' gives runtime exception

scala,gradle,akka,minecraft,minecraft-forge
I'm trying to use akka inside my scala based mod. The when testing using "gradle runClient" it gives errors, best I can tell its missing the akka library at runtime. I don't see how to add akka library though. If it helps my project is here: https://github.com/tesract/NilCraft Any advice would...

How to instantiate lexical.Scanner in a JavaTokenParsers class?

scala,parsing,lexical-scanner
I am writing a parser which inherits from JavaTokenParsers in that I have a function as follow: import scala.util.parsing.combinator.lexical._ import scala.util.parsing._ import scala.util.parsing.combinator.RegexParsers; import scala.util.parsing.combinator.syntactical.StdTokenParsers import scala.util.parsing.combinator.token.StdTokens import scala.util.parsing.combinator.lexical.StdLexical import scala.util.parsing.combinator.lexical.Scanners import scala.util.parsing.combinator.lexical.Lexical import...

How to effectively get indices of 1s for given binary string using Scala?

scala,functional-programming,higher-order-functions
Suppose we have a binary string such as 10010010. All I want is a function returning indices of 1s for that string: indicesOfOnes("10010010") -> List(0, 3, 6) indicesOfOnes("0") -> List() And what I implemented is: def indicesOfOnes(bs: String): List[Int] = { val lb = ListBuffer[Int]() bs.zipWithIndex.foreach { case (v, i)...

Is this definition of a tail recursive fibonacci function tail-recursive?

scala,f#,functional-programming,tail-recursion,continuation-passing
I've seen around the following F# definition of a continuation-passing-style fibonacci function, that I always assumed to be tail recursive: let fib k = let rec fib' k cont = match k with | 0 | 1 -> cont 1 | k -> fib' (k-1) (fun a -> fib' (k-2)...

Slick column mapper java.sql.Time to Joda LocalTime

scala,jodatime,slick
Looking to map java.sql.time to some joda time class. Having some issues with the mapper, it throws an error message. Has anyone performed this conversion? trait DateMapper { implicit val DateMapper = MappedColumnType .base[java.sql.Time, org.joda.time.LocalTime] ( d => new LocalTime(d.getTime)) } Error Unspecified value parameters: tcomap:(LocalTime) => Time ...

Providing implicit value for singletons in Play Json library

json,scala,playframework,scala-macros
I have following configuration: sealed trait Status case object Edited extends Status case object NotEdited extends Status case class Tweet(content:String, status:Status) I want to use Play Json format, so I guess I have to have something like this(I don't want to do it in companion object): trait JsonImpl{ implicit val...

Scala: Better way for String Formatting to PhoneNumber and using Java's MessageFormat

scala,formatting,messageformat
I'm looking for a better way to better implement the following: I have imported import java.text.MessageFormat to set the format I would like. val szphoneFrmt holds the format I would like. val szInitialString is set to the value I pulled from the database. val szWorkString breaks up the string via...

How to apply ordering to a Scala Priority Queue?

algorithm,scala,priority-queue
I've defined a priority queue like so import scala.collection.mutable.PriorityQueue ... val queue = new PriorityQueue[(Int,Int)]() I want to use this ordering: If we are comparing two items A and B in the queue, A is bigger than B if the first element of its (Int,Int) tuple is larger than B's....

Scala running issue on eclipse

eclipse,scala
I configured everthing within eclipse for scala. I create a snippet to show you the issue, i can't see in run options run as scala application, i also tried to find my main class under build configuration option but i can't find it. How i can solve it?...

Limit An Iteration By A Predicate

scala
I can generate a list of values by repeatedly applications of a function on the previously generated value as follows: List.iterate(math.Pi, 3)(x => math.sin(2*x)) List[Double] = List(3.141592653589793, -2.4492935982947064E-16, -4.898587196589413E-16) In this case, the iteration will stop when the length of the list is three. Is there a function in the...

Access key from mapValues or flatMapValues?

scala,apache-spark
In Spark 1.3, is there a way to access the key from mapValues? Specifically, if I have val y = x.groupBy(someKey) val z = y.mapValues(someFun) can someFun know which key of y it is currently operating on? Or do I have to do val y = x.map(r => (someKey(r), r)).groupBy(_._1)...

Implicit Generic.Aux missing on conversion from Shapeless HList to case class

scala,shapeless,type-level-computation
I just recently started learning scala and today I decided I wanted to write a CSV parser that would load nicely into case classes but store the data in rows (lists) of Shapeless's HList object so that I could get some exposure to type-level programming. Here's what I have so...

How to import directory of .scala files in sbt (unmanaged)?

scala,import,dependencies,sbt
I have a directory that I want to use as a dependancy for an sbt project however its comprised of .scala files which means I can't place it inside a jar (from what I understand) so then how can I use it as a dependancy for my project? (sbt doesn't...

Play Framework: How to get the current port number

scala,playframework
How do I get the current port number in a Play application? I use scala.

Scala slf4j dynamic file name

scala,logging,slf4j
I just successfully added Grizzled-SLF4J logger to my project using this link http://alvinalexander.com/scala/how-to-log-output-file-grizzled-slf4j-scala-simplelogger.properties But using this properties, there is no option to create dynamic file name: org.slf4j.simpleLogger.logFile = /tmp/myapp.log org.slf4j.simpleLogger.defaultLogLevel = info org.slf4j.simpleLogger.showDateTime = true org.slf4j.simpleLogger.dateTimeFormat = yyyy'/'MM'/'dd' 'HH':'mm':'ss'-'S org.slf4j.simpleLogger.showThreadName = true...

Scodec: Coproducts could not find implicit value for parameter auto: scodec.codecs.CoproductBuilderAuto

scala,scodec
I am trying to define an Scodec coproduct codec for communicating with an EELink GPS. Here is the code: import scodec.Codec import scodec.bits.ByteVector import scodec.codecs._ trait Message object Message { implicit val discriminated: Discriminated[ Message, Int ] = Discriminated(uint8) val codec: Codec[ Message ] = Codec.coproduct[ Message ].discriminatedByIndex(uint8) } case...

How to generalize the round methods

scala
I have the following four methods, using BigDecimal to round a number: private def round(input: Byte, scale: Int): Byte = { BigDecimal(input).setScale(scale, RoundingMode.HALF_UP).byteValue() } private def round(input: Short, scale: Int): Short = { BigDecimal(input).setScale(scale, RoundingMode.HALF_UP).shortValue() } private def round(input: Int, scale: Int): Int = { BigDecimal(input).setScale(scale, RoundingMode.HALF_UP).intValue() } private def...

How to make an sbt task run on under multiple scopes

scala,sbt
I have written an sbt plugin that generates some sources and resources. It is hard coded to work in the Compile scope. How can I make it work in the Test scope too, so I can use the plugin when running tests and it will look in and output to...

Spark-submit class not found exception

scala,apache-spark
I am trying to run this simple spark application with the spark submit command using this quick start tutorial. http://spark.apache.org/docs/1.2.0/quick-start.html#self-contained-applications. when I try to run it using spark-1.4.0-bin-hadoop2.6\bin>spark-submit --class " SimpleApp" --master local[4] C:/.../Documents/Sparkapp/target/scala- 2.10/simple-project_2.10-1.0.jar I get the following exception: java.lang.ClassNotFoundException: SimpleApp at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown...

How to change HTTP status code of AsyncResult using Scalatra

scala,akka,scalatra
I have created a simple controller (the code below is obfuscated and simplified, assume ask returns a future with a message). What I am trying to do is change the HTTP code from something other than 200 (based on the actor result). When executing the code below I see the...

Scala - Having trouble with filter & vals

scala
Working on an exercism.io exercise in Scala. Here is my current code: case class Allergies() { def isAllergicTo(allergen:Allergen.Allergen, score:Int) = { if (score < allergen.value || score == 0) false else true } def allergies(score:Int) = { val list = List(Allergen.Cats, Allergen.Pollen, Allergen.Chocolate, Allergen.Tomatoes, Allergen.Strawberries, Allergen.Shellfish, Allergen.Peanuts, Allergen.Eggs) list.filter(isAllergicTo(_, score)).sortBy(v...

Combining Spray Routing + Actor Pattern Matching

scala,akka,spray,akka-cluster
Following the Akka Cluster documentation, I have the Worker Dial-in example running. http://doc.akka.io/docs/akka/snapshot/java/cluster-usage.html So I've trying to integrate that with a spray routing. My idea is to have a cluster behind the scenes and through a http rest, call that service. So I have the following code. object Boot extends...

ZipList with Scalaz

list,scala,scalaz,applicative
Suppose I have a list of numbers and list of functions to apply to numbers: val xs: List[Int] = List(1, 2, 3) val fs: List[Int => Int] = List(f1, f2, f3) Now I would like to use an Applicative to apply f1 to 1, f2 to 2, etc. val ys:...

Spray microservice assembly deduplicate

scala,sbt,akka,spray,microservices
I'm using this template to develop a microservice: http://www.typesafe.com/activator/template/activator-service-container-tutorial My sbt file is like this: import sbt._ import Keys._ name := "activator-service-container-tutorial" version := "1.0.1" scalaVersion := "2.11.6" crossScalaVersions := Seq("2.10.5", "2.11.6") resolvers += "Scalaz Bintray Repo" at "https://dl.bintray.com/scalaz/releases" libraryDependencies ++= { val containerVersion = "1.0.1" val configVersion = "1.2.1"...

Scala rep separator for specific area of text

scala,parser-combinators
Imaging i've got following: --open Client: enter Nick Age 28 Rosewell, USA Client: enter Maria Age 19 Cleveland, USA --open-- I need a result close to the following: List(List(Nick, Age 28, Rosewell), List(Maria, Age19, Cleveland)) It can be as many clients inside open body as you can imagine, so the...

Expression of type Pointer[Float] doesn't conform to expected type Pointer[Float] in Scala

java,scala,bridj
I am new to Scala and I have been trying to use library bridj implemented in Java. Here is the code (allocateFloats is a method in class org.bridj.Pointer) import org.bridj.Pointer import org.bridj.Pointer._ class EstimatingPi { def main(args: Array[String]) { val n: Int = 1024 val aPtr : Pointer[Float] = allocateFloats(n)...

Type to impose required constrains on a double

scala,implicit-conversion
I would like to have a run time check on a Double, without having to scatter the check all over my code. I thought that defining an implicit class would do the job, something on the line: implicit class Probability(val x: Double) { require(x >= 0.0 && x <= 1.0,...

Scala: Convert a csv string to Array

arrays,string,scala,split,scala-collections
I tried to convert a scala string to array by splitting it by ,.For example: var string = "a,b,c,d," array = string.split(",") arr: Array[String] = Array(a, b, c, d) But the output I am getting is Array(a, b, c, d), instead of Array(a, b, c, d, ). The last comma...

Returning NonEmptyList `sealed trait`'s w/ scalaz.Validation

scala,scalaz,applicative
Given the following code: object Person { override def makePerson(name: String, age: Int, gender: Gender): Validation[NonEmptyList[InvalidPersonError], Person] = (validateName(name) |@| validateAge(age)) {_ ++ _} private def validateName(name: String): Validation[NonEmptyList[InvalidPersonError], String] = if(name.nonEmpty) name.successNel else InvalidName.failureNel private def validateAge(age: Int): Validation[NonEmptyList[InvalidPersonError], Int] = if(age >= 0) age.successNel else InvalidAge.failureNel sealed trait...

SBT won't pick the specified mainClass [duplicate]

scala,sbt
This question already has an answer here: How to set main class in build? 2 answers I wrote this scala code package com.abhi import java.io.File object Main1 { def main(args: Array[String]) : Unit = { println("Main1 Hello World") } } object Main2 { def main(args: Array[String]) : Unit =...

How to get notified when unfiltered Netty server actually gets shutdown?

scala,testing,netty,unfiltered
I have an Unfiltered Netty server that I need to shutdown and restart after every test. val mockService = unfiltered.netty.Server.http(mockServicePort).handler(mockServicePlan) before { proxyServer.start() } after { proxyServer.stop() } Currently, this is not working, and I am fairly certain that is because the stop() function is non-blocking and so the following...

Dynamic growth of `Actor`s vs Primal creation

scala,akka
In my project, I have defined groups of Actors called cells. Those cells process messages and operate basic calculations of some different kinds, one kind by small Actor type. What is the advantage(s) of growing those small Actors, then killing them once the job is done, rather than creating them...

Java encode raw bytes into image simple image fomat/ file

java,image,scala,image-processing
I am very new to image encoding and would rather not learn a whole lot about it. Basically I'm taking greyscale byte array where each byte equals one pixel. I'm getting this data from mnist where I get 28x28 byte images. Anyway, bellow is my code, so you understand what...

Implementing map on a tree using fold

scala,haskell
I am trying to implement a map using fold. I could do so in Haskell data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show) foldTree :: Tree a -> b -> (b -> a -> b -> b) -> b foldTree EmptyTree d _ =...

IntelliJ Plugin written in Scala - doesn't work

java,scala,intellij-idea,sbt,intellij-plugin
I want to develop my own IntelliJ plugin and I would like to do it using Scala language. When I use Java, everything work perfectly, but I'm not able to run a simple AnAction implemented in Scala. Have a look at these code samples, I have two AnAction implementations, one...

Scala first program issue

scala,recursion,case,frequency
I have just started to learn Scala after some experience with functional programming in other languages. def freq(c:Char, y:String, list:List[(Char,Int)]): List[(Char,Int)] = list match{ case _ => freq(c, y.filter(_ == c), list :: List((count(c,y),c))) case nil => list } In the above code I am getting an error when trying...

For-Comprehension Example with \/ and IO

scala,scalaz
Given the following Foo case class: scala> case class Foo(x: Int) defined class Foo I check if it's a valid Foo before constructing it inside of validateFoo: scala> def validateFoo(foo: Foo): \/[String, Foo] = (if(foo.x > 0) foo.success[String] else ("invalid foo").failure[Foo]).disjunction validateFoo: (foo: Foo)scalaz.\/[String,Foo] Lastly, f creates a Foo, and...

Scala (Slick) HList splitting to case classes

scala,slick
currently I have a HList with more than 22 fields and now I want to split it to 2-3 case classes, is there an easy functional way to do it? Currently I use the following syntax: CaseClass1(c.head, c.tail.head, c.tail.tail.head, etc...) However that doesn't seem to be right since I have...

How to unmarshall akka http request entity as string?

json,scala,akka-http
I'm trying to unmarshall request payload as string, but for some reason it's failing. My code: path("mypath") { post { decodeRequest { entity(as[String]) {jsonStr => //could not find implicit value for...FromRequestUnmarshaller[String] complete { val json: JsObject = Json.parse(jsonStr).as[JsObject] val jsObjectFuture: Future[JsObject] = MyDatabase.addListItem(json) jsObjectFuture.map(_.as[String]) } } } } } In...

Scala, how to set up a node class?

scala
Is there a resource for setting up a generic class in Scala? I am trying to make a segment tree where the node class contains a pointer to a left node, a pointer to a right node, and the value of the sum (and some other stuff but I think...

Instantiate type-parametrized class at runtime with default constructor

scala,reflection
I want to instantiate a new object with the following classes: class Test[T : ClassTag](val value : T) extends Serializable private object Test { private var testClass : Class[_] = _ def setTestClass(test : Class[_]) : Unit = { testClass = test } def apply[T : ClassTag](value : T) :...

implicit resolution for a function argument

scala,implicit,context-bound
I tried to implement mergesort in Scala. I got to the following: def mergeSort[A: Ordering](as: List[A]): List[A] = as match { case Nil => as case head :: Nil => as case _ => { val (l, r) = split(as) merge(mergeSort(l), mergeSort(r)) } } def split[A](as: List[A]): (List[A], List[A]) =...

Scala unapplySeq extractor syntax

scala,pattern-matching,scala-2.11
I (inadvertently) came across a bit of pattern matching syntax I did not expect to compile and now cannot figure out. It appears related to unapplySeq. Note the case x List(_,_) part in this simple example: val xs = List(1, 2, 3) //> xs : List[Int] = List(1, 2, 3)...

Preventing a class instantiation in Scala using Factory Pattern [duplicate]

scala,factory-pattern
This question already has an answer here: How to check constructor arguments and throw an exception or make an assertion in a default constructor in Scala? 2 answers Suppose that I have the following class defined in Scala: class ClassA(val n: Int) { ... } I want to limit...

Collapse similar case statements in Scala

scala,functional-programming,pattern-matching
Is there an elegant way to do something like the following example using just one case statement? foobar match { case Node(Leaf(key, value), parent, qux) => { // Do something with parent & qux } case Node(parent, Leaf(key, value), qux) => { // Do something with parent & qux (code...

spray.io upgrade causes missing mock library in specs2

scala,spray,specs2,spray-test
I use specs2 in my spray.io project. It all works fine and when I use the following versions. val akkaV = "2.3.6" val sprayV = "1.3.2" val specs2V = "2.3.11" However, recently I tried to upgrade the akka and spray version to the following. val akkaV = "2.3.9" val sprayV...

Wait for a list of futures with composing Option in Scala

scala,future
I have to get a list of issues for each file of a given list from a REST API with Scala. I want to do the requests in parallel, and use the Dispatch library for this. My method is called from a Java framework and I have to wait at...

convert scala object to json using json4s

json,scala,json4s
I have an ordinary scala class not a case class with many member variables including Buffers, Lists etc. I want to override the toString method of the class to give a json-string just like javascript's json.stringify() does. Is this possible with json4s? Because the only examples i have seen so...

Convert RDD[Map[String,Double]] to RDD[(String,Double)]

scala,apache-spark,rdd
I did some calculation and returned my values in a RDD containing scala map and now I want to remove this map and want to collect all keys values in a RDD. Any help will be appreciated....

Like clause not working with int column in slick

scala,slick,slick-2.0
Slick doesn't seem to support like clauses on int columns. The following code where Status.code is of int type doesn't seem to work. Would there be a workaround for this? val query = for { s <- Status if s.code like "1%" } yield (s) ...

Play Framework Form Error Handling

scala,playframework,playframework-2.3,playframework-2.4
This is my view file containing the form that has to filled in by the user: @helper.form(call) { @helper.input(resumeForm("surname"), '_label -> "Surname") { (id, name, value, args) => <input name="@name" type="text" value="@value" placeholder="Enter your surname"> } } This is my custom field constructor: @(elements: helper.FieldElements) @if(!elements.args.isDefinedAt('showLabel) || elements.args('showLabel) == true)...

How to reuse MappedColumnType in Table classes?

scala,playframework,slick
The use of MappedColumnType is demonstrated in this example: https://github.com/playframework/play-slick/blob/master/samples/computer-database/app/dao/ComputersDAO.scala#L21 How can I reuse dateColumnType in another table class?...

Creating a new File in Scala with PrintWriter

scala
I have created a function to create a file. My goal is to pass in a json string and return a new File with the contents of the json string passed into it. I am calling this function in another function as: val jsonFile: File = JsonCreate.getJsonFile(jsonString) So far, the...

Is there any scala library that treat tuples as monads

scala,tuples,monads
Is there any scala library that enriches basic scala tuples with monad syntax. Something similar to the Writer monad but adjusted for usage with tuples. What I look for: val pair = (2, "as") pair >>= (a => point(a+1)) should equal to (3, "as"). As well as for (p <-...

Scala official documentation Variances example code

scala
On http://docs.scala-lang.org/tutorials/tour/variances.html there is sample code scala> class Stack[+A] { | def push[B >: A](elem: B): Stack[B] = new Stack[B] { | override def top: B = elem | override def pop: Stack[B] = Stack.this | override def toString() = elem.toString() + " " + Stack.this.toString() | } | def...

Future yielding with flatMap

scala
Given Futures fa, fb, fc, I can use f: Function1[(A,B,C), Future[D]], to return a Future[D] either by: (for { a <- fa b <- fb c <- fc } yield (a,b,c)).flatMap(f) which has the unenviable property of declaring the variables a,b,c twice. or a.zip(b).zip(c).flatMap{ case (a, (b, c)) => f(a,...