My thoughs on Kotlin

3 08 2011

As a JetBrain’s Fan boy

I’m totally fan of JetBrain’s products. I’m using IntelliJ since the 4.0 version, even I develop a plugin for it. And seriously guys, this people know A LOT of programming languages; JetBrains develop IDE’s for Java, Python, (J)Ruby, HTML, JavaScript, PHP (originally developed by the community) , Objective C/C++, and have plugins for Groovy, Scala, AspectJ, ActionScript/Flex, SQL, JSP (including EL and JSTL), ERB, HAML, LESS, SASS, XML, YAML, Velocity, FreeMarker, Django Templates, Clojure, CFML (same as PHP) and many others. (without count, .Net products)

The development API for those IDE’s is so powerful that the community already contribute with many others (Including some esoteric languages): Arc, Bash, Erlang (this plugin is developed in Scala, EPIC geek) Fantom (very good plugin, seems to be abandoned, 😦 ), Gosu, Go (exists plans to develop a stand alone IDE using the IntelliJ Community Edition), JFlex, Lua, OCaml, Scheme, Power Shell and many others. Those plugins vary in quality from WOW to Eww!!, but is a good indicator for the quality of the language support on JetBrains products.

But, also Kotlin isn’t the first language that JetBrains develop. BaseLanguage is the language that come with MPS (Meta Programming System). MPS is a implementation of Language Oriented Programming paradigm. In plain English with MPS you can develop your own DSL and the MPS IDE will give you support, How? Extending the BaseLangauge (or creating a new one if you want). MPS isn’t too mainstream (A Hipster tool) but is already battle tested. YouTrack The JetBrain’s issue tracker was developed with MPS.

I think that we’re in good hands, JetBrains have all the experience and the knowledge to create a very good language, and of course with SUPER COOL IDE support from day 0. Also the feedback of the community is HUGE in the Kotlin Site. If JetBrains could embrace the community and listen them, they could develop a very successful language.

As a Scala Fan boy

I love Scala, Scala is my new best friend. I learn in two years with Scala more Computer Science than in five years with Java. Scala is a beautiful language that never end to inspiring me and amazing me (also scaring me).  Since I develop with Scala I’m a better developer; my code, even in others languages, seems to be more thread safe, more functional; but also Scala makes me a better son, citizen  and brother. Scala will lead us to a new golden age of prosperity and peace, a new renaissance of arts and philosophy. A beautiful new world.

But, let’s face the truth (please brothers of the Scala church, don’t kill me as a blasphemous) Scala’s complexity isn’t a Myth. (But I don’t agree with Gavin King)

Let me explain. If you come from a first world country with a very good High School program and Computer Science program like Swiss, Sweden or Norway; Scala isn’t complicated, but for people like me, that come from a third world country, with a Educational System “a little below the average” is complicated. I found myself studying countless hours to have “a little below the average” proficiency with Scala, I’m not complaining, was a VERY fun time, but, seriously guys is complicated.

Scala is more complicated than Java. Sure, you can use Scala as better Java, but is like buy a Lamborghini Gallardo to recharge your iPod, yes it’s works, but you’re losing a lot of features. In the other hand Kotlin IS a better Java, with good additions. A Java developer will be proficient in Kotlin in a fraction of the time, compared with Scala.

But Scala and Kotlin don’t need to be mortal enemies, If we can achieve a good interoperability between Kotlin, Java and Scala, we can have polyglot projects, so we can use the right language for the right type of problem. Also if you want to learn Scala a very natural way will be Java -> Kotlin -> Scala.

As an IntelliJ Scala plugin user

I think that the Scala support IntelliJ support is very good. Some great names in the Scala community are using IntelliJ and they are happy with it. Some FUD spread around the community with the announce of Kotlin thinking that maybe JetBrains will stop the development of the Scala plugin. Guys, this is the real world; the Scala plugin helps JetBrains to sale many IntelliJ licenses… JetBrains never will stop to develop the plugin as long as be good for business. Period

As a IntelliJ Power user

Obviously I use IntelliJ every day, but also I develop plugins. If JetBrains could use Kotlin to be more efficient in their developments all the users will win. But also they can test their new toy in a very hard scenario (Believe me guys, IDE’s are on of the most challenging scenarios for a language, and a developer).

As a business man

I have my own company (an one-man-army operation) I’m the Chairman, CEO, CTO, Sales manager, Development manager, Help Desk operator, architect, developer and tester. If I want to survive competing with other companies (big and small) I need a extra advantage, a secret weapon. My secret weapons are my tools (for more info on the subject you can read this post from Paul Graham). With IntelliJ, Spring Framework, Spring Integration and others, I actually defeat some bigger companies, with more developers, resources and money; delivering projects in a fraction of the time and costs with more quality. Scala provides me a huge competitive advantage… as long as I work alone.

But my little baby is growing, in less than a year I’ll  contract a few developers to achieve more bigger projects. Teaching Scala to a development team could be very challenging and frustrating and I COULD lose part of my advantage. But Kotlin seems to be a safer bet, More similar to Java, better integration, better IDE support, a huge productivity boost compared to Java… Kotlin could give more business value than Scala… heartbreaking history but true

But also if the language is successful (and have all the factors to be a success) there’s a lot of opportunity business waiting for us: Books, conferences, seminars, courses, libraries, tools, frameworks, certifications, t-shirts, mousepads, mugs and others, in fact a new beautiful world.

Advertisements




Scala on Stripes/Spring(II)

26 07 2009

Well the past chapter was very well received

Now we will continue with the DAO layer, and will learn more advanced Scala concepts

The DAO Layer

My friends know that I’m a “SQL Boy” I never need to learn ORM (I try many times, but the laziness beat me) so I’ll use Spring JDBC. If you don’t know this technology I’ll encourage you too take a look, this is one of the best parts of Spring. Spring JDBC take out the pain of JDBC in a very easy way, in fact I participate on a project where we migrate a bunch of Classic JDBC DAO’s for Spring DAO’s and the code was reduced in a 70%.

ScalaSimpleJdbcDaoSupport.scala

This class is a Support Class that extend SimpleJdbcDaoSupport to make more easy the work with Scala. In this class we are writing a little utility function in order to provide support for the methods with (Object… args) that SimpleJdbcTemplate have. Also we are writing some functions to wrap the SimpleJdbcTemplate; in a Real Case Scenario you need to write a lot of methods more

package com.simpletasks.dao.impl
import java.util.List
import org.springframework.jdbc.core.simple.{SimpleJdbcDaoSupport, ParameterizedRowMapper}
abstract class ScalaSimpleJdbcDaoSupport extends SimpleJdbcDaoSupport {
//
private def buildObjectArray(params: Any*): Array[Object] =     params.map(_.asInstanceOf[Object]).toArray
//
def queryForObject[T](sql: String, mapper: ParameterizedRowMapper[T], params: Any*): T =
getSimpleJdbcTemplate.queryForObject(sql, mapper, buildObjectArray(params: _*))
//
def query[T](sql: String, mapper: ParameterizedRowMapper[T], params: Any*): List[T] =
getSimpleJdbcTemplate.query(sql, mapper, buildObjectArray(params: _*))
//
def update(sql: String, params: Any*): Int =
getSimpleJdbcTemplate.update(sql, buildObjectArray(params: _*))
}

  • line 04 abstract: Same as Java
  • line 07 Any: Any is Scala as Object is a Java, all the Scala Classes including Basic Types are subclasses of Any
  • line 07 Repeated Parameters: The Asterisk (*) symbol is like Ellipsis/Varags (…) in Java. This means that you could add the parameters that you want, but is different in Java in some ways first of all, In Java you can call a method with an Array of the same type of the varargs argument, this isn’t possible in Scala; the second difference, In Java, in the method body the varargs argument is an Array, in Scala is a Seq. Seq is the base for a bunch of Collections in Scala, and provide some nice functions
  • line 07 Arrays: the Array in Scala is different from the Java Array; first of all the declaration type:
    In JavaString[]in ScalaArray[String]second, the access
    In JavamyArray[0]In ScalamyArray(0)Third, the implicit constructor
    In Java{0,1,2,3,4,5}In ScalaArray(0,1,2,3,4,5)
  • line 08 map function: the map function return a new Seq (remember that Scala is a OO/functional language, so you will be a lot of immutable classes like this) after applying some algorithm to all his members
  • line 08 High order functions:: A HOT feature, High order functions are lovely functions that take functions as parameters and/or return functions. (Geek Fun). In this case map take a function that will be applied in all the Seq’s members, (in our case, we are casting all the members to Object) this type of functions are very common in Scala Collections and produce a very neat and elegant code
  • line 08 The Placeholder strikes back: Our friend is representing the Seq member that we are casting.
  • line 08 Casting: The casting in Scala is a function invocation
  • line 08 Square Braces []: Most of the time that you’ll see Square Braces ([]) in Scala are around a Type, in fact this is the way that we define Type parameterization (Generics in Java) for that reason we declare Array[String] instead of String[]
  • line 08 (again) toArray function: toArray is a function that convert this little Seq in an Array (pretty evident), Look that I call this function without parenthesis.
  • line 10 Type parameterization [T]: This is the equivalent to <T> in Java, but Scala Type parameterization have enough power (and beautiful concepts like, variance, co-variance and contra-variance, I told you Scala is a funny language) too put Java Generics in shame (Martin Odersky, The Scala Father was the co-designer of Java Generics). But… sorry the whole power of Type Parameterization is outside of the scope of this humble tutorial.
  • line 13 : _* This is a little “syntactic hack”, if we call our function buildObjectArray with the params Seq, we are passing the Seq and not the Seq members. with : _*, we are passing the members one by one.

Well A lot of concepts for a simple class. This is all for now, in the next chapter we will use this class and learn about Traits, Bye, bye.





Scala on Stripes/Spring (I)

12 07 2009

All the cool kids on the block are talking about Scala. Is Scala the next big thing? the Golden Hammer?

The Hype is justified

First of all, yes, the hype is justified, Scala is a gorgeous language: powerful, elegant and fun.

Not the same “fun” that bring us Python or Groovy, is more an “Intellectual Fun”. Scala have many features and constructs that can teach a lot of Computer Science and language design, maybe more than another language, and for a Geek like me this is a lot of fun

But, beware, as the Uncle Ben Parker says: “With great power comes great responsability”. Scala is a very complex language, some times Scala is overwhelming. Personally I (think that) dominate Java in 3 years including a SCJP: easily Scala will take me 2 or 3 times to tame. Scala have features that, poorly used, can make your code a mess, and is probably that you can’t read your own code in six months. So is necesary a good amount of discipline and good praxis

In the other side of the coin, this mean a long (and fun) way of learning and auto discovery that’s will keep you interested for a long, long time

Why Stripes/Spring if exists Lift?

I most confess that I don’t know Lift more than a couple of quicks looks at Lift’s Site, seems good but the Maven thing scare me a lot, but the most important reason is simple; I’m a Big Fan of Stripes/Spring. I spend the last 3 years on both frameworks, So, Why throw away all my hard earned experience, if I can use both frameworks with Scala?

Lets code

Many tutorials have an academic approach, but for some people is more easy with an example project, this is the approach with this tutorial. Although I’m not a Scala expert, I’ll try to do the best I can

The Project

In IntelliStripes’s repository we have a toy project that we use to make functional test, you can see the java code
in http://code.google.com/p/intellistripes/source/browse/#svn/trunk/functional-test
or use a SVN Client to checkout

This project is a “bare bones” web app for Task Management (very original), nothing fancy here just create an account, create your tasks and delete them

The Domain (or is the model??)

We have 2 simples entities User and Task, just simple java beans

User.scala

package com.simpletasks.domain
/**
* Created by IntelliJ IDEA.
* User: Mario Arias
* Date: 15/05/2009
* Time: 10:09:57 PM
*/
class User {
  private var id: Int = 0
  private var email: String = _
  private var password: String = _
  private var name: String = _
  private var lastName: String = _
  def getEmail: String = email
  def setEmail(email: String) = this.email = email
  def getId: Int = id
  def setId(id: Int) = this.id = id
  def getLastName: String = lastName
  def setLastName(lastName: String) = this.lastName = lastName
  def getName: String = name
  def setName(name: String) = this.name = name
  def getPassword: String = password
  def setPassword(password: String) = this.password = password
  override def toString: String = "User{" +
    "email='" + email + '\'' +
    ", id=" + id +
    ", password='" + password + '\'' +
    ", name='" + name + '\'' +
    ", lastName='" + lastName + '\'' +
    '}'
}

Java version

Let’s see line by line and go deeper in Scala concepts on the way.

  • Scala Files: In Java you need to declare the file with the same name of a public class (interface, enum) in Scala you don´t have the same limitation. You can have several classes, even many packages, or an entire application in one file, I don’t know if you can want this, but is posbile, in the other side, navigate into this files could be frustrating
  • line 00 Packages: packages in scala have the same sintax that in java, but also you can declare as the namespaces in C#. Example:
    package com{
      package simpletaks.domain{
      }
    }
  • line 01 Comments: Same as Java.
  • line 07 Access Modifiers: All is public by default, but also exists private and protected. Access Modifiers are more powerful than in Java, but for now is enough. More on this later
  • line 07 Class Declaration:Similar to Java, More on this later
  • line 08 Look ma’ no semicolons:Scala don’t need semicolons, but you can add them if you want
  • line 08 Vars: The var keyword means that this field will change in the time, in other words is a variable (D’oh)
  • line 08 Type:The type of a field or a method is declared after the name and separated with colon
  • line 08 (Not So)Primitives:Scala don’t have primitives; all in Scala is an object, so the concept here is called basic types. The basic types are
    Byte 8-bit signed two’s complement integer (-27 to 27 – 1, inclusive)
    Short 16-bit signed two’s complement integer (-215 to 215 – 1, inclusive)
    Int 32-bit signed two’s complement integer (-231 to 231 – 1, inclusive)
    Long 64-bit signed two’s complement integer (-263 to 263 – 1, inclusive)
    Char 16-bit unsigned Unicode character (0 to 216 – 1, inclusive)
    String a sequence of Chars
    Float 32-bit IEEE 754 single-precision float
    Double 64-bit IEEE 754 double-precision float
    Boolean true or false
  • line 08 Assign: Same as Java
  • line 09 Placeholder:You’ll see the _ character a lot in Scala code, this is a placeholder and have many, many uses, in this case is the same as null. But why you want to assign null to a field?. ’cause in Scala when you don’t assign a value to a field is the same as have and abstract method in Java; In fact do you need to declare abstract your Scala class. In conclusion an abstract Scala class could have abstract fields or methods. This is weird coming from the Java world, but is pretty useful
  • line 13 Function declaration:All the functions (methods) in Scala start with the def keyword
  • line 13 Look ma’ no parenthesis (neither braces, nor return):Well that’s is less code, but all have and explanation, the lack of parenthesis = absence of parameters, the lack of braces = one-line function, the lack of return = pretty similar to Groovy, the last line of a function is the return; but like Groovy you can made the return explicit
  • line 14 Look ma’ no void:Yes and not, remember that scala is functional/object language, so all functions have a return type, in the case that function return nothing, the type of the function is Unit. So the same could be declared as def setEmail(email: String):Unit = this.email = email.
  • line 13 and 14 Getters and Setters and @BeanProperty Hot topic. Many of you will blame me for write myself Getters and Setter when I could use the @BeanProperty and write less code just like this @BeanProperty
    private var id:Int = 0
    and voila!! the compiler will generate a nice shiny get/set pair for me… you read well the compiler, thats mean that I cannot invoke this get/set pair on my own code, for me is almost useless, but a lot of people like this approach. Before you start to complain that I could declare the var as “public” and call it directly, I remember you that this is a Scala on Stripes/Spring tutorial and I need too use this class in the JSP so I need the get/set pair
  • line 23 Function override:When you need override a function, you must add the keyword override this must will protect you from accidentally override a function without know.
  • line 23 String concat:Same as Java, but with a great difference… in fact this is not a string concat… this is only a function invocation. "Hello " + "World" is the same as "Hello ".+("World"). So in Scala do you have operator overloading; and this is how the concat happens. Then you can call any one-parameter function without the dot and the parenthesis. if the function have many parameters you can call without the dot, but with parenthesis

Task.scala
package com.simpletasks.domain
import java.util.Date
class Task {
  private var id: Int = 0
  private var title: String = _
  private var detail: String = _
  private var finished: Boolean = false
  private var createDate: Date = _
  private var endDate: Date = _
  def getCreateDate: Date = createDate
  def setCreateDate(createDate: Date) = this.createDate = createDate
  def getDetail: String = detail
  def setDetail(detail: String) = this.detail = detail
  def getEndDate: Date = endDate
  def setEndDate(endDate: Date) = this.endDate = endDate
  def getId: Int = id
  def setId(id: Int) = this.id = id
  def getTitle: String = title
  def setTitle(title: String) = this.title = title
  def isFinished: Boolean = finished;
  def setFinished(finished: Boolean) = this.finished = finished
  override def toString: String = "Task{" +
    "createDate=" + createDate +
    ", id=" + id +
    ", title='" + title + '\'' +
    ", detail='" + detail + '\'' +
    ", finished=" + finished +
    ", endDate=" + endDate +
    '}';
}

Java Version

  • line 01 Imports Similar in to Java, but a little more powerful. If you need to import two class of the same package you only need a line import java.util.{Date,List} But if you need all the classes on a package, our old friend placeholder will help us import java.util._. More on this topic in the next chapters.

UserNotFoundException.scala
package com.simpletasks.domain.exceptions
class UserNotFoundException extends Exception

Java Version

  • line 01 extends: The extends keyword is similar to Java, but have little differences, but in this tutorial we don’t touch this concept very deeply.
  • line 01 Look ma’ no braces: You don’t need to add braces if your class don’t have a body

Is ok for now, maybe this chapter isn’t so exciting, but I promise you that the next chapters will be bring some OOOHHH, and many WOWWWW. In the next chapter we’ll use some Spring JDBC and take a closer look to the Scala Syntax.





Wise Java LOLcat choose IntelliJ

9 07 2009
Wise Java LOLcat choose IntelliJ

Wise Java LOLcat choose IntelliJ