Posty

Wyświetlanie postów z październik, 2018

Ruby vs Kotlin: Custom Comparable classes

Often it's nice to be able to sort custom objects and compare which one is bigger or smaller. Today we are going to implement such MyDate class in Ruby and Kotlin. I found it interesting that interfaces in Kotlin, similarly to modules in Ruby, can contain an implementation. Let's see a very simple example.

First in Ruby:

class MyDate < Struct.new(:year, :month, :day_of_month)
  include Comparable

  def <=>(other)
    diff_year = year - other.year
    return diff_year if diff_year.nonzero?

    diff_month = month - other.month
    return diff_month if diff_month.nonzero?

    day_of_month - other.day_of_month
  end
end

def check_in_range(date, first, last)
  Range.new(first, last).cover?(date)
end


and now in Kotlin.

data class MyDate(
  val year: Int, 
  val month: Int, 
  val dayOfMonth: Int
) : Comparable {
    override operator fun compareTo(other: MyDate): Int {
        val diffYear = year - other.year
        if (diffYear != 0) { return diffYear }

        val diffMonth = month - other.mo…

Ruby vs Kotlin syntax for lambdas

The same code expressed in Kotlin

orders.flatMap{ it.products }
orders.flatMap(Order::products)
orders.flatMap{ o -> o.products }

and Ruby:

orders.flat_map(&:products)
orders.flat_map{|o| o.products }